How to use new Function() Constructor In Javascript
Similar to eval(), you can also use the new Function() constructor to parse JSON data. However, this method also executes the code passed to it, making it susceptible to security vulnerabilities.
Syntax:
let parseJson = new Function('return ' + jsonString + ';');
let jsonObject = parseJson();
Example: Parsing the Person JSON data using the new Function() method.
let jsonString = '{"name": "ABC", "age": 30}';
let parseJson = new Function('return ' + jsonString + ';');
let jsonObject = parseJson();
console.log(jsonObject.name);
console.log(jsonObject.age);
Output
ABC 30
How to Parse JSON Data in JavaScript ?
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write. It is easy for machines to parse and generate it. In JavaScript, parsing JSON data is a common task when dealing with APIs or exchanging data between the client and server.
Table of Content
- Using JSON.parse() Method
- Using eval() Function
- Using new Function() Constructor