How do I convert object to JSON in JavaScript?

To convert an object to a JSON string in JavaScript, you can use the JSON.stringify(value, replacer, space). The JSON.stringify() method serializes objects, arrays, or primitive values into a JSON data string. In this JavaScript object to JSON conversion example, we serialize the JavaScript object to JSON and pretty-print the generated JSON string. Click Execute to run the JavaScript Object to JSON Example online and see the result.
How do I convert object to JSON in JavaScript? Execute
let obj = {
  "client": "Alice",
  "age": 31,
  "city": "London",
  "interests": ["football", "hiking", "gym"]

console.log(JSON.stringify(obj, null, 2))
Updated: Viewed: 759 times

What is JSON?

JavaScript Object Notation (JSON) is a language-independent text format for holding and exchanging data. Developers use JSON to exchange data between a web browser and a server and exchange data between servers via REST API. There are ready-made code libraries for creating and manipulating JSON data for many programming languages, including JavaScript, Java, C ++, C #, Go, PHP, and Python. JSON file names use the .json file extension.

JSON Example
  "Id": 78912,
  "Customer": "Jason Sweet",
  "Quantity": 1,
  "Price": 18.00

Convert object to JSON using JSON.stringify() method

The JSON.stringify(value, replacer, space) method in JavaScript converts objects and arrays into a JSON string. Depending on the requirements, JSON.stringify(value, replacer, space) can produce minified or pretty JSON strings. Minified JSON is useful when sending data over the network, and pretty JSON is useful when analyzing serialized objects by humans. Below is an example of converting an object to JSON with the JSON.stringify() method:

JavaScript Convert Object to JSON with JSON.stringify() Example
let obj = {
  "id": 2,
  "customer": "Jack",
  "city": "Paris"


// output: {"id":2,"customer":"Jack","city":"Paris"}

See also