Convert JSON String to Array of JSON Objects in JavaScript
Last Updated :
28 May, 2024
Given a JSON string, the task is to convert it into an array of JSON objects in JavaScript. This array will contain the values derived from the JSON string using JavaScript. There are two approaches to solve this problem, which are discussed below:
Approach 1: Using JSON.parse() Method
The basic method to convert JSON String to Array of JSON object is by using JSON.parse() method. This method is used to parse a JSON string which is written in a JSON format and returns a JavaScript object.
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 }
]
Approach 2: Using JavaScript eval() Method
The eval() method parse a JSON string and then converts it into an array of objects. However, using eval() method is not recommended due to potential security risks, as it can execute arbitrary code.
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.
Please Login to comment...