Convert a JSON String to Object using JavaScript


Borislav Hadzhiev

Last updated: Oct 31, 2021


Photo from Unsplash

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 #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.