How can I convert a JavaScript object to JSON and vice versa?
Davide S
davide s profile pic

To convert a JavaScript object to JSON (JavaScript Object Notation) and vice versa, you can use the built-inJSON object in JavaScript. TheJSON object provides two important methods: 1.JSON.stringify(): - TheJSON.stringify() method converts a JavaScript object to a JSON string. - It accepts three parameters: -value: The JavaScript object to be converted. -replacer (optional): A function or an array used to filter and transform the result. -space (optional): A string or a number to control the spacing in the JSON string. - Example:

1
2
3
4
5

     const obj = { name: "John", age: 30 };
     const jsonStr = JSON.stringify(obj);
     console.log(jsonStr); // Output: '{"name":"John","age":30}'
     

2.JSON.parse(): - TheJSON.parse() method converts a JSON string to a JavaScript object. - It accepts a single parameter: -text: The JSON string to be parsed. - Example:

1
2
3
4
5

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

By using these methods, you can easily convert JavaScript objects to JSON strings and vice versa. It's important to note that the objects being converted must be compatible with JSON's data types: string, number, object, array, boolean, or null. Functions and undefined values cannot be directly converted to JSON. Here's an example that demonstrates both conversions:

1
2
3
4
5
6
7
8
9
10

const obj = { name: "John", age: 30 };

// Convert object to JSON string
const jsonStr = JSON.stringify(obj);
console.log(jsonStr); // Output: '{"name":"John","age":30}'

// Convert JSON string to object
const parsedObj = JSON.parse(jsonStr);
console.log(parsedObj); // Output: { name: 'John', age: 30 }

In the example above, theobj object is first converted to a JSON string usingJSON.stringify(), and then the JSON stringjsonStr is converted back to a JavaScript object usingJSON.parse().