How to parse a JSON Array in JavaScript


Borislav Hadzhiev

Sun Oct 31 20212 min read

Parse a JSON Array in JavaScript #

Use the JSON.parse() method to pase a JSON array, e.g. JSON.parse(arr). 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 jsonArr = '[{"id": 1, "name": "Tom"}, {"id": 2, "name": "Alice"}]'; const parsed = JSON.parse(jsonArr); // ๐Ÿ‘‡๏ธ [{id: 1, name: 'Tom'}, {id: 2, name: 'Alice'}] console.log(parsed);

We used the JSON.parse method to parse a JSON array into its JavaScript equivalent.

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

If you provide invalid JSON to the method, a SyntaxError exception is thrown.

const invalidJson = '[{id: 1}]'; // ๐Ÿ‘‡๏ธ๏ธ Unexpected token i in JSON at position 2 console.log(JSON.parse(invalidJson));
The JSON array in the example does not have double quotes around the idproperty, which makes it invalid.

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

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

const jsonArr = '[{"id": 1, "name": "Tom"}, {"id": 2, "name": "Alice"}]'; let parsed; try { parsed = JSON.parse(jsonArr); console.log('โœ… JSON array parsed successfully'); } catch (err) { console.log('โ›”๏ธ invalid JSON provided'); // report error } // ๐Ÿ‘‡๏ธ [{id: 1, name: 'Tom'}, {id: 2, name: 'Alice'}] console.log(parsed);

If the provided JSON is invalid, our catch block will run, where we can handle the error.

If the JSON is valid, it gets parsed and assigned to the parsed variable.

If your JSON is invalid, google for a JSON validator and paste it in the text box.

See what errors your JSON contains and correct them - either on the server, or use the String.replace or String.replaceAll methods to correct them on the client.

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

const invalidJson = "['apple', 'banana']"; const validJson = invalidJson.replaceAll(`'`, `"`); // ๐Ÿ‘‡๏ธ {'apple', 'banana'} const parsed = JSON.parse(validJson); console.log(parsed);

We used the replaceAll() method to replace all occurrences of single quotes with double quotes to make the JSON array 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.

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