📜  javascript json stringify indented - Javascript (1)

📅  最后修改于: 2023-12-03 15:01:37.896000             🧑  作者: Mango

JavaScript JSON.stringify() with Indentation

When working with JSON data in JavaScript, it is often necessary to convert the data to a string using the JSON.stringify() method. By default, this method returns a JSON string with no indentation, making it difficult to read and debug. However, you can add indentation to the output string by passing an optional parameter to the JSON.stringify() method.

Syntax

The syntax of the JSON.stringify() method with indentation is as follows:

JSON.stringify(obj, replacer, space)

The space parameter is what controls the indentation of the output string. It can accept a number or a string value.

If space is a number, it specifies the number of spaces to use for indentation. For example, if you want to use four spaces for each level of indentation, you can set space to 4.

If space is a string, it specifies the characters to use for indentation. For example, if you want to use a tab character for indentation, you can set space to '\t'.

Example

Here is an example of using the JSON.stringify() method with indentation:

const data = {
  name: 'John',
  age: 30,
  hobbies: ['reading', 'coding'],
  address: {
    street: '123 Main St',
    city: 'Anytown',
    state: 'CA'
  }
}
// without indentation
const jsonString = JSON.stringify(data);
console.log(jsonString);

// with indentation using spaces
const jsonIndentSpaces = JSON.stringify(data, null, 4);
console.log(jsonIndentSpaces);

// with indentation using tabs
const jsonIndentTabs = JSON.stringify(data, null, '\t');
console.log(jsonIndentTabs);

Output:

{"name":"John","age":30,"hobbies":["reading","coding"],"address":{"street":"123 Main St","city":"Anytown","state":"CA"}}
{
    "name": "John",
    "age": 30,
    "hobbies": [
        "reading",
        "coding"
    ],
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "state": "CA"
    }
}
{
	"name": "John",
	"age": 30,
	"hobbies": [
		"reading",
		"coding"
	],
	"address": {
		"street": "123 Main St",
		"city": "Anytown",
		"state": "CA"
	}
}

As you can see from the output, the indentation makes the JSON data much easier to read and understand.

Conclusion

In conclusion, the JSON.stringify() method with indentation is a powerful tool that can make working with JSON data in JavaScript much easier. By using the space parameter, you can control the number of spaces or characters used for indentation in the output string.