HOWTO · React
How to Parse JSON Strings in React
Learn how to parse JSON strings in React effectively. This article covers essential methods like JSON.parse(), fetching data from APIs, and using async/await for cleaner code. Enhance your skills in handling JSON data and improve your React applications with these practical techniques.
On this page
A React component works with JavaScript values such as objects and arrays, while an API or a file may provide JSON as text. Parsing converts that text into a JavaScript value you can inspect and render. For an existing string, use JSON.parse(); for a Fetch response body, use the asynchronous response.json() method.
Understand JSON parsing in React
JSON is a text format for representing values such as objects, arrays, strings, numbers, booleans, and null. A JSON object looks similar to a JavaScript object, but it is still text until it is parsed. For example, '{"name":"Ada","city":"London"}' is a string; after parsing, its name property can be read as Ada.
Parsing and serialization go in opposite directions: JSON.parse(jsonText) turns JSON text into a JavaScript value, while JSON.stringify(value) turns a serializable JavaScript value into JSON text. React does not need a special parser. Parse data before using its properties in a component, and keep asynchronous requests out of the component’s render body.
Parse a JSON string with JSON.parse()
Use JSON.parse() when you already have a string containing valid JSON. It returns the corresponding JavaScript value, so an object can be accessed with ordinary property notation. JSON requires double quotes around object keys and string values; JavaScript-only syntax such as comments, single-quoted strings, and trailing commas is not valid JSON.
Run this example:
const jsonText = '{"name":"Ada","role":"Engineer"}';
const person = JSON.parse(jsonText);
console.log(person.name);
Ada
The parser can return an object, array, string, number, boolean, or null, depending on the JSON text. If the text is malformed, JSON.parse() throws a SyntaxError. When the string comes from outside your application, handle that failure where parsing occurs; see the error section below.
Create and parse a local JSON example
If your data starts as a JavaScript object, serialize it to JSON text with JSON.stringify() and then parse that text to recover a JavaScript value. This illustrates both directions, but it is not necessary to stringify data that is already JSON text.
const original = { product: "Notebook", price: 12 };
const jsonText = JSON.stringify(original);
const restored = JSON.parse(jsonText);
console.log(`${restored.product}: $${restored.price}`);
Notebook: $12
Serialization only includes values supported by JSON. For example, object properties whose values are functions or undefined are omitted. For data received as a JSON string, skip JSON.stringify() and parse the string directly.
Render parsed data in JSX
Parse a known JSON string before the component’s return so the conversion is easy to find and errors can be handled separately. Then use the resulting value like any other JavaScript object. For example, after defining const person = JSON.parse(jsonText), a component can render the name with <p>{person.name}</p>.
JSX curly braces evaluate JavaScript expressions; they do not parse JSON by themselves. Keep the JSON text and parsed value in clearly named variables, and render only the properties the interface needs. If the parsed value can be null or have a different shape, check it before reading nested properties.
Fetch and parse JSON in a React component
A call to fetch() resolves to a Response; it does not directly return the parsed data. Check response.ok to detect HTTP error statuses, then call and await response.json() to read the body and parse it. The result is a promise for a JavaScript value. This differs from JSON.parse(), which takes a string you already have.
In a React component, start the request in an effect and store its result in state. The following is a pattern to adapt in a React application; it is framework-specific and is not a standalone example for the article’s runtime:
useEffect(() => { let ignore = false; async function load() { try { const response = await fetch('/api/profile'); if (!response.ok) throw new Error('Request failed: ' + response.status); const profile = await response.json(); if (!ignore) setData(profile); } catch (error) { if (!ignore) setError(error); } } load(); return () => { ignore = true; }; }, []);
The cleanup flag prevents a completed request from updating state after the effect has been cleaned up. In an application, define the relevant state with useState, and replace the example endpoint with one that returns JSON. A successful HTTP status with a body that is not valid JSON can still make response.json() reject.
Handle parsing and request errors
JSON.parse() can fail on malformed text. Catch the parsing error at the point where untrusted text is converted, then choose a useful fallback or show an error message rather than assuming the result is an object.
const jsonText = '{"name":';
let person;
try {
person = JSON.parse(jsonText);
} catch (error) {
console.log(error instanceof SyntaxError ? "Could not read JSON" : "Unexpected error");
}
Could not read JSON
Fetch requests have separate failure paths. Network failures reject the fetch() promise, while an HTTP response such as 404 normally still fulfills it; check response.ok and handle a false value. Parsing the response body can also fail if it is not valid JSON. Put the status check and response.json() inside the same try block so the component can present an error state for each failure.
Display fetched data with React state
Keep request status and fetched data in React state, then render the state that applies. A component can begin with a loading message, show an error when the request or parsing fails, and render the data after success. For example, conditional rendering can follow this shape: if (error) return <p role="alert">Could not load profile.</p>; if (data === null) return <p>Loading…</p>; return <p>{data.name}</p>; Initialize state and choose a loading representation that fits the API’s possible response values.
Do not start a request or call JSON.parse() as a side effect during render. Render should use the current state; an effect performs the request and updates that state when it completes. This keeps the UI responsive and makes loading, success, and error behavior explicit.