Converting JavaScript Object to JSON

Converting JavaScript Object to JSON

JavaScript Object Notation (JSON) is a lightweight data interchange format that is easy to read and write. It is often used to transmit data between a client and a server. Converting a JavaScript object to JSON is a straightforward task that can be accomplished in a few different ways.

Method 1: Using the JSON.stringify() Method

The easiest way to convert a JavaScript object to JSON is by using the built-in JSON.stringify() method. This method takes an object as its parameter and returns a JSON string.


let obj = { name: "Jane", age: 30 };
let json = JSON.stringify(obj);
console.log(json); // {"name":"Jane","age":30}

In the above example, we have defined an object with two properties, name and age. We then pass this object to the JSON.stringify() method, which returns a JSON string that represents the object.

Method 2: Using the JSON.parse() Method

If you have a JSON string and you want to convert it back to a JavaScript object, you can use the JSON.parse() method. This method takes a JSON string as its parameter and returns a JavaScript object.


let json = '{"name":"Jane","age":30}';
let obj = JSON.parse(json);
console.log(obj); // { name: "Jane", age: 30 }

In the above example, we have defined a JSON string that represents an object with two properties, name and age. We then pass this JSON string to the JSON.parse() method, which returns a JavaScript object that represents the JSON string.

Method 3: Using a Custom Function

If you have a more complex object that cannot be easily converted using the JSON.stringify() method, you can write a custom function to convert it to JSON. This method involves iterating over the object's properties and manually constructing a JSON string.


function convertToJSON(obj) {
  let json = '{';
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      json += '"' + key + '":';
      if (typeof obj[key] === 'object') {
        json += convertToJSON(obj[key]);
      } else {
        json += '"' + obj[key] + '"';
      }
      json += ',';
    }
  }
  json = json.slice(0, -1);
  json += '}';
  return json;
}

let obj = { name: "Jane", age: 30, address: { street: "123 Main St", city: "Anytown" } };
let json = convertToJSON(obj);
console.log(json); // {"name":"Jane","age":30,"address":{"street":"123 Main St","city":"Anytown"}}

In the above example, we have defined an object with three properties, name, age, and address. The address property is itself an object. We then pass this object to the convertToJSON() function, which recursively iterates over the object's properties and constructs a JSON string.

These are some of the common ways of converting a JavaScript object to JSON. Depending on your specific use case, one of these methods may be more appropriate than the others.

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