javascript How to convert String to JSON object

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 for 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 into the object, and has a parse() method that accepts string text, parses JSON string, and converts it to a JavaScript object Here is an example of converting to a 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(; // 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);
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.