2 ways to convert String to JSON object in javascript? (Example)
- Admin
- Mar 10, 2024
- Javascript Javascript-convert
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, a String in JavaScript is a group of characters enclosed in single or double quotes. JSON is an object of key and value pairs enclosed in double quotes. It is an important task for a developer to convert to JSON and face many issues during development.
Convert String to JSON object in JavaScript
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 built into a JavaScript 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(jsonObject.name); // Franc
console.log(jsonObject.department); // sales
In the example above,
- String contains a JSON employ object with valid json text.
- Printed string variable to the console using typeof operators and printed as a string
- parse string and convert to JSON object using inbuilt
JSON.parse()
method - Console the object type and an object printed
- you can access json object properties using
object.keys
- Printing individual property keys of json objects using jsonobject.key
syntax
If JSON text is not well-formatted or is invalid format, Then it throws SyntaxError: Unexpected token n in JSON at position 1.
To handle such errors, use try and catch block In the below example, the name
property missing start "
symbol start.
try{
const employee = '{name": "Franc","department":"sales"}';
console.log(typeof employee);
var jsonObject = JSON.parse(employee);
} catch (error) {
console.error('JSON parse failed:', error);
}
The advantages of this approach are using inbuilt JavaScript objects, and not requiring any libraries.
Using the JQuery parseJSON method
JQuery parseJSON
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.
Conclusion
To summarize, Learned how to parse
- String to JSON object using JSON.parse in Javascript
- using jQuery library