Converting JSON to JavaScript Object

Converting JSON to JavaScript Object

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is used to transmit data between a server and a web application, as an alternative to XML.

Converting a JSON string to a JavaScript object can be done in many ways:

Using JSON.parse() method:

The most popular way to convert JSON to a JavaScript object is to use the built-in JSON.parse() method. This method takes a JSON string as input and returns a JavaScript object.

const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const obj = JSON.parse(jsonString);
console.log(obj); // Output: {name: "John", age: 30, city: "New York"}

Using Function Constructor:

You can also convert JSON to JavaScript object using the Function constructor. This technique involves creating a new Function object with the input JSON string as its body and then invoking the function using the eval() method. This approach is not recommended because it can be dangerous if the input string is not trusted.

const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const obj = new Function('return ' + jsonString)();
console.log(obj); // Output: {name: "John", age: 30, city: "New York"}

Using jQuery:

If you are using jQuery in your web application, you can use the $.parseJSON() method to convert JSON to JavaScript object.

const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const obj = $.parseJSON(jsonString);
console.log(obj); // Output: {name: "John", age: 30, city: "New York"}

Using JSON.parse() with try-catch block:

If you are not sure if the input string is a valid JSON string, you can use the try-catch block to handle any errors that may occur during the conversion process.

const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
let obj;
try {
  obj = JSON.parse(jsonString);
} catch (error) {
  console.error(error);
}
console.log(obj); // Output: {name: "John", age: 30, city: "New York"}

By using one of these techniques, you can easily convert JSON string to JavaScript object. Always be careful while working with JSON data as it can be manipulated easily.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe