How to Convert Object into String in JavaScript?

JSON object (JavaScript Object Notation) has many hidden features for parsing, stringifying, prettifying, formatting and hiding some properties. To convert a JavaScript object into a JSON string, we use the JSON.stringify() method. It is the opposite of JSON.parse(), which converts JSON into JavaScript Objects. In this JSON tutorial, we will learn how to use JSON.stringify() with many interesting examples. Also, learn how to customise serialization with arrays and replacer functions.

JSON.stringify()

The JSON.stringify() is a static method in JavaScript that converts a JavaScript object into a JSON string. Values can be replaced or filtered if a replacer function is specified to include certain key-value pairs from the object, the process known as serialization.

Databases and other data stores usually don’t have a built-in feature to interpret JavaScript. JSON.stringify() acts as a bridge between JavaScript objects and the data sources that hold them.

Syntax

JSON.stringify(value)
JSON.stringify(value, replacer)
JSON.stringify(value, replacer, space)
  • value: A JavaScript value that is to be converted into JSON String.
  • replacer (optional): A function or an array that is used to customize the behaviour of the stringification process.
  • space (optional): A whitespace string (or a number) that specifies the indentation level for the output JSON string. It is mostly used to format the output so that it is in readable form. If provided, it must be a string with a maximum of ten spaces or a non-negative number, if it is omitted or null then no whitespace is added which results in a more compact JSON string.

Example 1: Converting Object into a JSON String

Now, let’s take a code snippet and convert an object into a JSON string.

const obj = { name: 'Jai', age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString);
Converting Object into a JSON String

As we can see, the code produces a JSON string representation of the object, basically, it is an object which is represented as a long string.

Example 2: Converting Nested Objects into String

JSON.stringify() is able to handle various types of nested objects and data types seamlessly such as string, numbers, boolean, arrays and nested objects. Look at the below snippet to understand this better:

const nestedObj = {
    name: 'Ali',
    age: 25,
    address: {
        city: 'New York',
        zip: 10001
    }
};

const jsonString = JSON.stringify(nestedObj);
console.log(jsonString);
Converting Nested Objects into String

As we can see from the above snippet, the JSON.stringify() method has completed its successful iteration over the nested objects within ‘nestedObj’ and properly serialized each nesting level.

Customizing Serialization with Arrays

The second parameter of JSON.stringify() is the ‘replacer’ allows us to specify an array of properties that we want to include in the output of the JSON string. This feature is useful when we have an object with multiple attributes, but we only want to include a few of them in the JSON representation.

const person = [{
        name: 'Ali',
        age: 25,
        job: 'Engineer',
        salary: 50000
    },
    {
        name: 'Aman',
        age: 27,
        job: 'Data Engineer',
        salary: 50000
    }
]
const jsonString = JSON.stringify(person, ['name', 'job']);
console.log(jsonString);
Customizing Serialization with Arrays

In this example, you can see that we have used the replacer array as we need to modify the object. As a result, the output JSON string contains only the properties that we have specified.

Customizing Serialization with Functions

We can also pass a function as the second parameter, i.e. replacer function, inside the JSON.stringify() method to specify which properties of the input object should be included in the output JSON string.

const person = {
    name: 'Alice',
    age: 25,
    job: 'Engineer',
    salary: 50000
};

const jsonString = JSON.stringify(person, (key, value) => {
    if (key === 'age') {
        return value * 2; // doubling the age
    }
    return value; // default behavior for other properties
});
console.log(jsonString);
Customizing Serialization with Functions

In this example, the replacer function determines if ‘age’ is the property that is serialized and if so, the method adds the age value to the JSON string after doubling it. All other attributes are included by default, and they are not altered.

Conclusion

JSON.stringify() is like a translator for JavaScript objects. It turns them into a special kind of text that computers can easily read and share with each other. Furthermore, customizing serialization with JSON.stringify() increases the flexibility and usefulness of the JSON.stringify() method in JavaScript. It is recommended to convert JavaScript object into JSON string, before performing any further operations. We hope you enjoyed it.

Also Read:

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Adarshita Gupta
Adarshita Gupta
Articles: 10