Open In App

Convert JSON String to Array of JSON Objects in JavaScript

Last Updated : 04 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Converting a JSON string to an array of JSON objects in JavaScript involves transforming a structured text format (JSON) into a usable JavaScript array. This allows developers to work directly with the data, enabling easier manipulation, analysis, and display of information.

1. Using JSON.parse() Method

Using the JSON.parse() method, a JSON string can be easily converted into an array of JSON objects in JavaScript. This method interprets the string and returns a JavaScript array, enabling developers to work directly with the structured data programmatically.

JavaScript
// JSON String Representing an Array of Objects
const jsonStr = '[{"name": "Adams", "age": 30}, {"name": "Davis", "age": 25}, {"name": "Evans", "age": 35}]';

// Parse JSON string to array of objects
const jsonArray = JSON.parse(jsonStr);

// Output the array of objects
console.log(jsonArray);

Output
[
  { name: 'Adams', age: 30 },
  { name: 'Davis', age: 25 },
  { name: 'Evans', age: 35 }
]

2. Using JavaScript eval() Method

The eval() method in JavaScript can convert a JSON string into an array of objects by evaluating the string as code. However, it’s highly discouraged due to security risks, as `eval()` can execute arbitrary code, potentially making the application vulnerable to attacks.

JavaScript
// JSON String Representing an Array of Objects
const jsonStr = '[{"name": "Adams", "age": 30}, {"name": "Davis", "age": 25}, {"name": "Evans", "age": 35}]';

let obj = eval('(' + jsonStr + ')');

let res = [];

for (let i in obj)
    res.push(obj[i]);

console.log(res);

Output
[
  { name: 'Adams', age: 30 },
  { name: 'Davis', age: 25 },
  { name: 'Evans', age: 35 }
]

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Next Article

Similar Reads

three90RightbarBannerImg