{

javascript How to convert/parse String object to JSON object


Convert/parse String to JSON object in JavaScript

Convert/parse String to JSON object in JavaScript

In JavaScript, when the user submits 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, Learn 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 data enclosed in single quotes.
It is an important task as a developer to convert to JSON and face many issues during development.

For a given string

const employee = '{"name": "Franc","department":"sales"}';  

There are two ways we can convert to a JSON object.

  • JSON.parse() method
  • JQuery parseJSON method

Using JSON.parse() method

JSON is inbuilt in the 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 operators and printed as an object
  • parse Json text and convert to JSON object using inbuilt JSON.parse() method
  • Console the object type and print an object printed
  • object.
  • Printing individual property keys of json objects 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, the name property missing " symbol start.

const employee = '{name": "Franc","department":"sales"}';  
  
console.log(typeof employee)  
  
var jsonObject = JSON.parse(employee);  

The advantages of this approach are using inbuilt JavaScript objects, and not requiring any libraries.
Using JQuery parse JSON method
parseJSON in jquery also does the same, but you have to include the JQuery library.

var jsonStr = '{"name":"kiran"}';  
var obj = jQuery.parseJSON(jsonStr); or  
var obj = $.parseJSON(jsonStr);  

parseJSOn also throws an error, if json text is invalid format.

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

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.