How to parse a JSON Array in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

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.

index.js
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 is the JSON string that should be parsed.

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

index.js
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 id property, which makes it invalid.

The JSON.parse method attempts to parse the JSON, but is unable to do so 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 your program doesn't crash.

index.js
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 runs, 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.

index.js
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 is the replacement for each match.

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.