This is another JavaScript tutorial, This tutorial help to Parse JSON in JavaScript.We will convert JSON String into JSON object using JSON.parse. I also demonstrate how to convert JSON Object into json strings using JSON.stringify method.
The Backend server-side application has rest api. The Rest API is used by the Client application to get data from the server. The Rest API uses JSON data format to exchange data from the server and client-side application, The framework internally has JSON encode and decode format data in JSON.
But here, I will describe how to convert string-type data into JSON data. Normally, the client received data in string format, which need to convert the string into JSON data, JSON help to process data easily. The JSON.parse() method helps to parse json data from string. The JavaScript JSON.parse() is a synchronous type method that means it execution time is proportional to data size, But with help of JavaScript event loop concept, You can make Asynchronous JSON parsing request using setTimeout call.
You can also check other tutorials on JSON Object,
- jQuery jqGrid Example with JSON Data Using Rest Service
- Live search on JSON Objects Data Using jQuery
- How to Process/Iterate on JSON Objects in JavaScript
- JSON data Object Uses and Example using Javascript
How To Parse JSON in JavaScript Using JSON.parse()
Let’s create a simple string of data that have employee data, Like:
'{ "employee_name":"Adam", "age":25, "salary":"11111"}'
We will use JSON.parse()
method into the above string data. The below code will convert a string into JSON key-value pair data.
let emp = JSON.parse('{ "employee_name":"Adam", "age":25, "salary":"11111"}');
You can access the above json data using object properties like emp.employee_name
, emp.age
and emp.salary
.
The JavaScript parse json result is:
{ "employee_name":"Adam", "age":25, "salary":"11111"}
Convert JSON Data into String Using JavaScript JSON.stringify()
Parsing json in JavaScript is very simple and easy. The JavaScript provides JSON.stringify()
function, This method will convert the JavaScript JSON Object into the json String.
The employee json data is :
{ "employee_name":"Adam", "age":25, "salary":"11111"}
We will convert JSON data into the strings:
let emp = { "employee_name":"Adam", "age":25, "salary":"11111"}; let str_emp = JSON.stringify(emp);
The JavaScript JSON stringify result is:
'{ "employee_name":"Adam", "age":25, "salary":"11111"}'
How To Parse JSON in jQuery
The jQuery has $.parseJSON()
method to parse JSON, This method worked before the jQuery 3, The jquery 3 has been deprecated $.parseJSON()
method. You can parse JSON strings into JSON data using JavaScript the native JSON.parse method in jQuery 3.
The below method works only for jquery < 3:
var obj = jQuery.parseJSON( '{ "employee_name":"Adam", "age":25, "salary":"11111"}' ); alert( obj.employee_name );