parse json in javascript

In JavaScript, we can parse a json string using the built-in JSON.parse() method. This method takes a string as input, and returns the parsed json object.

Here's an example:

index.tsx
const jsonString = '{"name": "John", "age": 30, "city": "New York"}';
const jsonObj = JSON.parse(jsonString);
console.log(jsonObj);
132 chars
4 lines

Output:

index.tsx
{
  name: "John",
  age: 30,
  city: "New York"
}
50 chars
6 lines

We can also convert a JavaScript object to a json string using the JSON.stringify() method.

Here's an example:

index.tsx
const jsonObj = {name: 'John', age: 30, city: 'New York'};
const jsonString = JSON.stringify(jsonObj);
console.log(jsonString);
128 chars
4 lines

Output:

index.tsx
{
  "name": "John",
  "age": 30,
  "city": "New York"
}
56 chars
6 lines

Note that JSON.parse() will throw a SyntaxError if the input string is not valid json.

related categories

gistlibby LogSnag