简体   繁体   English

javascript JSON响应格式

[英]javascript JSON response formatting

Folks, Trying to understand returning and forming JSON responses. 伙计们,试着理解返回和形成JSON响应。

The following code returns the object as a single string: 以下代码将对象作为单个字符串返回:

res.send(JSON.stringify(data));

Output to the browser: 输出到浏览器:

{"Count":1,"Items":[{"dbsource":{"S":"x"},"number":{"S":"5002820"},"name":{"S":"blah,foo"},"expiration":{"S":"06/13/2015"},"type":{"S":"bar"}}]}

Dont I want the JSON output to be more readable, ie : 我不希望JSON输出更具可读性,即:

{
"one": "two",
"key": "value"
}

What should i change JSON.stringify(data) to? 我应该将JSON.stringify(数据)更改为什么? Ideally I want the response to be used as an API endpoint. 理想情况下,我希望将响应用作API端点。

Thanks! 谢谢!

You are almost there. 你快到了。 Use stringify with spaces 将stringify与空格一起使用

var str = JSON.stringify(data, undefined, 2);

The above string will have indentation with 2 spaces. 上面的字符串将有2个空格的缩进。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM