JavaScript JSON

JSON is widely used as a data interchange format and is supported by most of the modern programming languages including JavaScript, Python, Java, C#, and many others.

In this tutorial, we will look at how to parse and generate JSON data in JavaScript.

Parsing JSON data

To parse a JSON string in JavaScript, you can use the JSON.parse method. This method takes a JSON string as an argument and returns a JavaScript object or array corresponding to the parsed JSON data.

Here's an example of how to parse a JSON string:

1let jsonString = '{"name": "William", "age": 30, "city": "New York"}'; 2let obj = JSON.parse(jsonString); 3console.log(obj.name); 4// Output: William

Generating JSON data

To generate a JSON string from a JavaScript object or array, you can use the JSON.stringify method. This method takes a JavaScript object or array as an argument and returns a JSON string corresponding to the input data.

Here's an example of how to generate a JSON string from a JavaScript object:

1let obj = {name: "William", age: 30, city: "New York"}; 2let jsonString = JSON.stringify(obj); 3console.log(jsonString); 4// Output: '{"name": "William", "age": 30, "city": "New York"}'

Note that JSON.stringify can also accept two optional parameters:

  • replacer: a function that transforms the values that are going to be stringified.
  • space: adds indentation, white space, and line break characters to the return string to format it.
1let obj = {name: "William", age: 30, city: "New York"}; 2let jsonString = JSON.stringify(obj, null, 4); 3console.log(jsonString); 4/* Output: 5{ 6 "name": "William", 7 "age": 30, 8 "city": "New York" 9} 10*/