How to make an array from JSON to JavaScript

Create an array from JSON in JavaScript: example included! Learn to parse and manipulate JSON data in JS.

Converting JSON to JavaScript Array

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write. It is commonly used for transmitting data in web applications. In order to convert JSON to a JavaScript array, we need to use the JSON.parse() method. The JSON.parse() method takes a JSON string and transforms it into a JavaScript object.

The syntax for the JSON.parse() method is as follows:


let array = JSON.parse(jsonString);

Where jsonString is a string containing a valid JSON object. It is important to note that the JSON.parse() method does not work on an already-constructed JavaScript object. The JSON.parse() method will convert a JSON string into an array.

For example, let's say we have the following JSON string containing a list of books:


let jsonString = '{"books": [{"title": "The Great Gatsby","author": "F. Scott Fitzgerald"},{"title": "The Catcher in the Rye","author": "J.D. Salinger"}]}';

We can use the JSON.parse() method to convert this JSON string into a JavaScript array:


let array = JSON.parse(jsonString);

console.log(array);
// Output: { books:
        //  [ { title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
        //  { title: 'The Catcher in the Rye', author: 'J.D. Salinger' } ] }

As you can see, the JSON.parse() method has converted the JSON string into a JavaScript array containing objects for each book. Now we can access each book object and manipulate it as needed.

In summary, the JSON.parse() method is a great way to convert a JSON string into a JavaScript array. It is important to note that the JSON.parse() method does not work on an already-constructed JavaScript object. It only works on a JSON string.

Answers (0)