乐闻世界logo
搜索文章和话题

How to pretty print json using javascript

4个答案

1
2
3
4

In JavaScript, you can use the JSON.stringify() method to convert JSON objects to their string representation, and this method also enables you to print JSON data in a highly readable format. JSON.stringify() accepts three parameters: the object to serialize, an optional replacer function, and an optional number or string to control indentation.

Here is an example demonstrating how to use the JSON.stringify() method to pretty-print a JSON object:

javascript
// Assume we have the following JSON object const myObject = { name: "John", age: 30, cars: ["Ford", "BMW", "Fiat"] }; // The third parameter controls indentation, with 2 indicating two spaces per level const prettyJson = JSON.stringify(myObject, null, 2); console.log(prettyJson);

The output will be:

shell
{ "name": "John", "age": 30, "cars": [ "Ford", "BMW", "Fiat" ] }

In this example, we are not using the replacer function (the second parameter of JSON.stringify()), but it can also be used to filter or transform values within the object. If you wish to customize the display of certain properties or exclude specific properties from being printed, you can provide this function.

For example, if you only want to print the second element of the cars array, you can do the following:

javascript
function replacer(key, value) { // If the key is 'cars', return only the second element of the array if(key === "cars") { return [value[1]]; } return value; } // Using a custom replacer function and indentation const prettyJson = JSON.stringify(myObject, replacer, 2); console.log(prettyJson);

The output will be:

shell
{ "name": "John", "age": 30, "cars": [ "BMW" ] }

This replacer function will only print "BMW" from the cars array. This approach is very useful when dealing with large objects or when you need to filter out sensitive information from the output.

2024年6月29日 12:07 回复

If you're looking for something like this:

javascript
JSON.stringify(obj, null, '\t');

This uses tabs for indentation to pretty-print your JSON string.

If you prefer spaces over tabs, you can specify the number of spaces using a number:

javascript
JSON.stringify(obj, null, 2);
2024年6月29日 12:07 回复

If you have an object you want to pretty-print, User Pumbaa80's solution is excellent. If you start with a valid JSON string that you want to pretty-print, you need to first parse it into an object:

javascript
var jsonString = '{"some":"json"}'; var jsonPretty = JSON.stringify(JSON.parse(jsonString), null, 2);

This parses the string into a JSON object and then pretty-prints it back to a string using JSON.stringify.

2024年6月29日 12:07 回复

你的答案