javascript convert object to json

javascript

To convert an object to a JSON string in JavaScript, you can use the JSON.stringify() function. Here’s an example:

const obj = {
  name: 'John',
  age: 30,
  city: 'New York'
};

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

You can also specify a replacer function as the second argument to JSON.stringify(), which allows you to modify the value that gets stringified. And you can use the third argument to specify a space to use for pretty-printing the output.

For example:

const json = JSON.stringify(obj, (key, value) => {
  if (key === 'age') {
    return value + 10;
  }
  return value;
}, 2);
console.log(json);
// Output:
// {
//   "name": "John",
//   "age": 40,
//   "city": "New York"
// }

This will add 10 to the age property when stringifying the object, and also pretty-print the output with 2 spaces of indentation.