How do I create a JSON string in JavaScript?

To create a JSON string in JavaScript, you can use the JSON.stringify(value, replacer, space) method. The JSON.stringify() method serializes (converts to string) objects, arrays, or primitive values ​​into a JSON string. The JSON.stringify() method takes three parameters. The first parameter is the object to be converted to a JSON string. The second optional parameter is a function that changes the behavior of the serialization process; if the value is blank or null, then all properties of the object are included in the string. The third optional parameter is an argument used to control the spacing in the final string; if this parameter is not specified then its value is "null". In this JavaScript JSON Stringify Example, we use the JSON.stringify() method to convert an object to a JSON string. Click Execute to run the JavaScript JSON Stringify Example online and see the result.
How do I create a JSON string in JavaScript? Execute
let obj = {
  "id": 78912,
  "customer": "Jason Sweet",
  "city": "Rome"
};

console.log(JSON.stringify(obj))
Updated: Viewed: 1091 times

What is JSON?

JavaScript Object Notation (JSON) is a text format for representing structured data based on the syntax of the JavaScript language. JSON file names use the .json file extension. JSON is usually used for data exchange between applications written in many programming languages, including JavaScript, Python, PHP, C++, Java, C#, Go, and many more.

JavaScript JSON.stringify() Method

The JSON.stringify(value, replacer, space) method in JavaScript the "value" object to a JSON string. The resulting JSON string is called a JSON-formatted or serialized object, which we can send over the network or put into a regular data store. Note that a JSON object has several important differences from literal objects: strings only use double quotes; object property names are enclosed in double-quotes.

JSON supports the following data types:

  • Objects {...}
  • Arrays [...]
  • Primitives: string, numbers, boolean values ​​true/false, null
JavaScript JSON.stringify() Syntax
JSON.stringify(value, replacer, space)

Where:
  • value: the value that is converted to a JSON string
  • replacer (optional): a function that changes the behavior of the serialization process or an array of property names to be serialized (serving as filtering the values ​​to include in the JSON string). If this value is null or not specified, then all of the object's properties are included in the resulting JSON string. The function can take two parameters - a key and a value.
  • space (optional): a string or numeric value used to insert spaces into the output JSON string for readability. If it is a numeric value, then it specifies the number of spaces before each converted property.

JavaScript JSON.stringify() Examples

Basic JSON.stringify() Example:

JavaScript JSON.stringify() Example
let obj = {
  "Spain": "Madrid",
  "Italy": "Rome",
  "Portugal": "Lisbon"
};

console.log(JSON.stringify(obj))

// output: {"Spain":"Madrid","Italy":"Rome","Portugal":"Lisbon"}

Customizing the JSON.stringify() process

In most cases, the JSON.stringify() method is only used with the first argument. But if we need to customize the replacement process, such as filtering out circular references, then we can use the second argument of the JSON.stringify() method. If we pass it an array of properties, only those properties will be encoded.

JavaScript JSON.stringify() Customizing Example
let obj = {
  Id: 78912,
  Customer: [{name: "Jason"}, {surname: "Sweet"}],
};

console.log(JSON.stringify(obj, ['Id', 'Customer', 'name', 'surname']))

// output: {"Id":78912,"Customer":[{"name":"Jason"},{"surname":"Sweet"}]}

Creating a pretty JSON string

The third parameter of the JSON.stringify(value, replacer, space) method is the number of spaces used for convenient formatting. Objects serialized in JSON format have no indentation or extra space by default. This is useful if we want to send the JSON string over the network and we need a small data size. The third space argument is used solely for human-readable output.

Creating a Pretty JSON String Example
let obj = {"Id": 78912, "Customer": "Jason Sweet","City": "Rome"};

console.log(JSON.stringify(obj, null, 2));

// output: 
// {
//   "Id": 78912,
//   "Customer": "Jason Sweet",
//   "City": "Rome"
// }

Creating a JSON String using the toJSON() method

Like toString() for converting strings, an object can provide a toJSON() method for converting to JSON. JSON.stringify automatically calls it if it exists. The toJSON() method is used both when calling JSON.stringify() directly and when an object is nested within another serializable object.

JSON String with toJSON() Example
let age = {
  age: 25,
  toJSON() {
    return this.age;
  }
};

let person = {
  name: "Jason Sweet",
  age
};

console.log(JSON.stringify(age)); 
// output: 25

console.log(JSON.stringify(person));
// output: {"name":"Jason Sweet","age":25}

How to decode JSON string?

In order to decode (parse) a string in JSON format and, you can use the JSON.parse() method:

JavaScript JSON.parse() Example
let obj = '{"id":78912,"customer":"Jason Sweet","city":"Rome"}';

obj = JSON.parse(obj);

console.log(obj.customer)

// output: Jason Sweet

See also