Convert a JSON String to Object using JavaScript


Borislav Hadzhiev

Sun Oct 31 20212 min read


Photo by Paz Arando

Convert a JSON String to Object in JavaScript #

Use the JSON.parse() method to convert a JSON string to object, e.g. JSON.parse(jsonStr). The method parses a JSON string and returns its JavaScript value or object equivalent. If the provided parameter is not valid JSON, the JSON.parse method throws a SyntaxError exception.

const jsonStr = '{"color": "blue", "number": 30}'; const parsed = JSON.parse(jsonStr); console.log(parsed); // ๐Ÿ‘‰๏ธ {color: 'blue', number: 30}

We used the JSON.parse method to convert a JSON string to an object.

The only parameter we passed to the method is the JSON string that should be parsed.

If you pass an invalid JSON string to the method, a SyntaxError exception is thrown.

const invalidJsonStr = "{'color': 'blue'}"; // โ›”๏ธ Error: Unexpected token ' in JSON at position 1 const parsed = JSON.parse(invalidJsonStr);
The JSON string in the example uses single quotes around the object's key and value, which makes it invalid.

The JSON.parse method attempts to parse the JSON string, but is unable to and throws an exception.

If you need to handle this scenario, you can use the JSON.parse method inside of a try/catch block to make sure your program doesn't crash.

const jsonStr = '{"color": "blue", "number": 30}'; let parsed; try { parsed = JSON.parse(jsonStr); console.log('โœ… JSON converted to object successfully'); } catch (err) { console.log('โ›”๏ธ invalid JSON provided'); }

If the jsonStr variable stores invalid JSON, the catch block will catch the exception so we can handle it.

If the JSON string is valid, it gets converted to an object and assigned to the parsed variable.

If your JSON string stores invalid JSON, copy the string and paste it into a JSON validator to see where the errors come from.

You can correct the errors either on the server, or on the client, by using the String.replace or String.replaceAll methods to replace/remove any invalid characters from the JSON string.

For example, the following code replaces all single quotes with double quotes to produce a valid JSON string.

const invalidJsonStr = "{'color': 'blue'}"; const validJsonStr = invalidJsonStr.replaceAll(`'`, `"`); // ๐Ÿ‘‡๏ธ {color: 'blue'} const parsed = JSON.parse(validJsonStr); console.log(parsed);
We used the replaceAll() method to replace all occurrences of single quotes with double quotes to make the JSON string valid.

The first parameter the replaceAll method takes is the substring we want to match in the string.

And the second - the replacement for each match.

The JSON.parse method was able to convert the JSON string to a JavaScript object.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee