Skip to main content

How to Convert JSON String to JSON Object using JavaScript

In our previous post we have seen compilation error related stuff, In this article we will see “How to Convert JSON String to JSON Object using JavaScript

In JavaScript there is a method called JSON.parse() to convert JSON string into JSON object. JSON is a commonly used data format for exchanging data between a server and web applications. It can be used in many ways for mobile and web development.

I will share an example here which will demonstrate how to convert JSON string into JSON object.

Here’s how I write code.

var jsonString = '[{'
	 +		'"id" : "EMP001",'
     +		'"name" : "James Code",'
     +		'"age"  : 25,'
     +		'"departmentname" : "Android"'
	 +		'"id" : "EMP002",'
     +		'"name" : "Rohit Sharma",'
     +		'"age"  : 32,'
     +		'"departmentname" : ".NET"'
	 +		'"id" : "EMP003",'
     +		'"name" : "Oggy",'
     +		'"age"  : 41,'
     +		'"departmentname" : "IOS"'

Run above javascript code in direct console and you can see the output as below

(3) [{…}, {…}, {…}]
0: {id: "EMP001", name: "James Code", age: 25, departmentname: "Android"}
1: {id: "EMP002", name: "Rohit Sharma", age: 32, departmentname: ".NET"}
2: {id: "EMP003", name: "Oggy", age: 41, departmentname: "IOS"}
length: 3
__proto__: Array(0)

Now you can use the JSON data for various purpose, like loop through all the element and display on the page, you can do some calculation also on that data before displaying on the page etc.

If you want to iterate through all the element in JSON object then see the below for loop example.

for (loop = 0; loop < jsonObject.length; loop++) {

Make sure that entered string must be in a correct JSON format or else it will give an error

That’s it. Thanks for reading my article.

152 total views, 1 views today

Tarun Dudhatra

Tarun is a writer of website. He is a software professional with hands on 10+ years of experience. Generally he writes an article about microsoft technology, Javascript, SQL Server and JQuery. Here he shares his notes, experiences, examples.