How to Convert JSON String to Array of JSON Objects in JavaScript

Here are two ways to convert JSON String to an Array of JSON Objects in JavaScript.

  1. Using JSON.parse( )
  2. Using eval()

Let’s check out both methods one by one.

Method 1: Using JSON.parse()

The JSON.parse() method is recommended to convert a JSON string into a JavaScript object or array. It’s safe, efficient, and specifically designed for this purpose.

const jsonString = `[{"name":"John", "age":30, "city":"New York"},
                     {"name":"Jane", "age":25, "city":"Los Angeles"}]`;

const jsonArray = JSON.parse(jsonString);

console.log(jsonArray);

Output

[
  { name: 'John', age: 30, city: 'New York' },
  { name: 'Jane', age: 25, city: 'Los Angeles' }
]

Method 2: Using eval()

The eval() function is used to evaluate a string of JavaScript code. While this means it can convert a JSON string into an object, it can also execute any arbitrary code contained in the string, which poses a significant security risk.

const jsonString = `[{"name":"John", "age":30, "city":"New York"},
                     {"name":"Jane", "age":25, "city":"Los Angeles"}]`;

const jsonArray = eval('(' + jsonString + ')');

console.log(jsonArray);

Output

[
  { name: 'John', age: 30, city: 'New York' }, 
  { name: 'Jane', age: 25, city: 'Los Angeles' }
]

WARNING: Using eval() can be very dangerous if the content of the string is not controlled or properly sanitized, as it could lead to malicious code execution. You should avoid using eval() for parsing JSON or any other purpose unless you have a specific need and are aware of the risks.

Conclusion

Always use JSON.parse() to convert JSON strings to JavaScript objects or arrays. It’s the safer and more efficient choice. Avoid using eval() unless you have a specific and justified reason and know the potential risks.

Leave a Comment