Friday, March 13, 2020

javascript example - How to convert/parse String object to JSON object | JQuery

Convert/parse String to JSON object in JavaScript

Convert/parse String to JSON object in JavaScript
 In JavaScript, when the user submitted the form, form data is collected in String format, We need to convert this to JSON object in the HTTP request to make REST API.
In this blog, we are going to discuss how to convert String objects to JSON objects. Generally, String in JavaScript is a group of characters enclosed in single or double-quotes.
JSON text in a string as a data enclosed in single quotes.
 This is an important task as developer to convert to JSON and faces many issues during development.

For a given string
const employee = '{"name": "Franc","department":"sales"}';
There are two ways we can convert to JSON object

  • JSON.parse() method 
  • JQuery parseJSON method 

 Using JSON.parse() method 

 JSON is an inbuilt in object, has parse() method accepts string text, It parses JSON string and converts to JavaScript object Here is an example for converting to JSON object.
console.log(typeof employee) //string 

var jsonObject = JSON.parse(employee);
console.log(typeof jsonObject) //object

console.log(jsonObject) //{ name: 'Franc', department: 'sales' }
console.log(jsonObject.name)  // Franc
console.log(jsonObject.department) // sales
In the example above,

  • employ object is declared assigned with valid json text. 
  • Printed json text type to console using typeof operator and printed as object 
  • parse Json text and  converted to JSON object using inbuilt JSON.parse() method
  • Console the object type and printed as object printed
  •  object.
  • Printing individual property keys of json object using jsonobject.key 
  • syntax 

 if json text is not well formatted or invalid format, Then it throws SyntaxError: Unexpected token n in JSON at position 1.
In the below example, name property missing " symbol start.
const employee = '{name": "Franc","department":"sales"}';

console.log(typeof employee)

var jsonObject = JSON.parse(employee);
The advantages with this approach is using inbuilt JavaScript object, not required any libraries.
Using JQuery parseJSOn method
 parseJSON in jquery also do the same, but you have to include JQuery library.
var jsonStr = '{"name":"kiran"}';
var obj = jQuery.parseJSON(jsonStr); or
var obj = $.parseJSON(jsonStr);
parseJSOn also throws error, if json text is invalid format.

 Please let me know your feed on this post and share this in social media.

Related article


EmoticonEmoticon