How to Convert a JSON String to a JavaScript Object

From WikiHTP

The JSON data format is derived from the JavaScript programming language. These two elements are therefore closely linked. It is possible to transform an object written in JSON into a JavaScript object thanks to different methods. JavaScript natively provides a method to directly create a JavaScript object from JSON.

JSON.Parse() Method[edit]

var json = '{first_name: Mark, last_name: Ford}';
var person = JSON.parse(json);
console.log (person.first_name + + person.last_name); // This line displays the text Marc Ford.

The eval() method can also interpret JSON and create a JavaScript object, but it is strongly discouraged to use it. This method interprets and executes the code passed as an argument without control. Its use can be hijacked to execute malicious code. The JSON.Parse() method is more secure and can not execute malicious code, it just interprets the JSON to create a JavaScript object. This method is not compatible with Internet Explorer 7. For this browser, the jQuery JavaScript library provides the $.parseJSON() method. This method is only available in versions of jQuery prior to version 3.

JSON.stringify() Method[edit]

It is also possible to perform the reverse operation: transform a JavaScript object into JSON notation. We use the JSON.stringify() method.

var person = new object();
person.first_name = Mark;
person.last_name = Ford;
var json = JSON.stringify(person);
console.log(json); // This line displays the text {first_name: Mark, last_name: Ford}.

You can also use external decoders / encoders to manage the JSON. The site dedicated to the JSON language references external libraries to manage the JSON format for most computer languages, including four libraries for JavaScript.

About This Tutorial

This page was last edited on 28 January 2019, at 06:34.