Skip to content
the poor coder

js create json from object

Poor Man
Published
Reading time
1 min read
On this page

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:#

JavaScript
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:#

JavaScript
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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC