json in javascript

In JavaScript, you can work with JSON data using the built-in JSON object. This object provides two methods for working with JSON data: JSON.stringify() and JSON.parse().

JSON.stringify()

The JSON.stringify() method takes a JavaScript object and returns a JSON string representation of the object. Here's an example:

index.tsx
const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

const json = JSON.stringify(person);

console.log(json); // '{"name":"John","age":30,"city":"New York"}'
172 chars
10 lines

JSON.parse()

The JSON.parse() method takes a JSON string and returns a JavaScript object. Here's an example:

index.tsx
const json = '{"name":"John","age":30,"city":"New York"}';

const person = JSON.parse(json);

console.log(person); // { name: 'John', age: 30, city: 'New York' }
162 chars
6 lines

Keep in mind that the JSON string must be valid JSON, otherwise a SyntaxError will be thrown.

gistlibby LogSnag