How to convert a JSON string into a JavaScript object


How to convert a JSON string into a JavaScript object

📋 Table Of Content

In this short article, we will learn how to convert a JSON string into a JavaScript object.

JSON (JavaScript Object Notation) is an open standard data format to store and transfer data across the web. A common use of JSON is to exchange data between web servers and the client browser.

When we receive data from the web servers it's in string format. So to use it on the site we need to convert it into an object first.

Convert JSON string to an object

To convert a JSON string to an object we can use the JSON.parse() method.

The JSON.parse() method receives the text from the web servers and converts it to an object.

Syntax:

JSON.parse(string)

Suppose we have received this string from the server.

'{"name":"Johnny", "id":5554, "city":"London"}'

So to use the data in our browser, we convert it to a JavaScript object using JSON.parse().

let text = '{"name":"Johnny", "id":5554, "city":"London"}'
const obj = JSON.parse(text)

console.log(obj)

Output:

{ 
  name: 'Johnny', 
  id: 5554, 
  city: 'London' 
}

Related Topic:

Difference Between JSON.Stringify() And JSON.Parse() In JSON

How To Covert JavaScript Object To JSON String

Beautify or pretty print JSON programmatically in JavaScript