how to parse a json string in javascript

To parse a JSON string in javascript, use the JSON.parse() method. This method takes a JSON string as an argument and returns a javascript object that represents the data in the JSON string.

index.tsx
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const obj = JSON.parse(jsonString);

console.log(obj.name); // Output: John
console.log(obj.age); // Output: 30
console.log(obj.city); // Output: New York
225 chars
7 lines

The JSON.parse() method can also be used with an array of JSON objects.

index.tsx
const jsonArray = '[{"name": "John", "age": 30}, {"name": "Jane", "age": 25}]';
const arr = JSON.parse(jsonArray);

console.log(arr[0].name); // Output: John
console.log(arr[1].age); // Output: 25
197 chars
6 lines

To convert a javascript object to a JSON string, use the JSON.stringify() method.

index.tsx
const obj = {name: "John", age: 30, city: "New York"};
const jsonString = JSON.stringify(obj);

console.log(jsonString); // Output: {"name":"John","age":30,"city":"New York"}
175 chars
5 lines

gistlibby LogSnag