js create json from object

How to Create JSON from an Object in JavaScript

JSON or JavaScript Object Notation is a lightweight data format that is easy to read and write. It is widely used in web applications to transmit data between the client and server. In JavaScript, you can create JSON from an object using the JSON.stringify() method. This method converts a JavaScript object into a JSON string.

Example:

const person = {
  name: 'Raju',
  age: 25,
  city: 'Bangalore'
};

const personJSON = JSON.stringify(person);

console.log(personJSON);
// Output: {"name":"Raju","age":25,"city":"Bangalore"}

In the above example, we have a JavaScript object named person with three properties - name, age, and city. We use the JSON.stringify() method to convert this object into a JSON string named personJSON. Finally, we log the JSON string to the console.

You can also pass a replacer function as the second argument to JSON.stringify() method to customize the conversion process. The replacer function can modify or filter out the properties of the object before they are included in the JSON string.

Example:

const person = {
  firstName: 'Raju',
  lastName: 'Kumar',
  age: 25,
  city: 'Bangalore'
};

const personJSON = JSON.stringify(person, (key, value) => {
  if (key === 'firstName') {
    return value.toUpperCase();
  }
  return value;
});

console.log(personJSON);
// Output: {"firstName":"RAJU","lastName":"Kumar","age":25,"city":"Bangalore"}

In the above example, we pass a replacer function as the second argument to JSON.stringify() method. The replacer function checks if the property name is firstName. If yes, it converts the value to uppercase using the toUpperCase() method. If not, it returns the value as it is. Finally, we log the modified JSON string to the console.

That's how you can create JSON from an object in JavaScript. Make sure to use the JSON.stringify() method and pass a replacer function as needed.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe