如果我在 JS 中定义了一个对象:
var j={"name":"binchen"};
如何将对象转换为 JSON?输出字符串应该是:
'{"name":"binchen"}'
原文由 Bin Chen 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果我在 JS 中定义了一个对象:
var j={"name":"binchen"};
如何将对象转换为 JSON?输出字符串应该是:
'{"name":"binchen"}'
原文由 Bin Chen 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 JSON.stringify()
在 json2.js 中找到或在大多数现代浏览器中都是原生的。
JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as "\t" or " "), it contains the characters used to indent at each level.
原文由 Ignacio Vazquez-Abrams 发布,翻译遵循 CC BY-SA 4.0 许可协议
10 回答11.1k 阅读
6 回答3k 阅读
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
所有当前的浏览器都内置了原生 JSON 支持。所以只要你不处理像 IE6/7 这样的史前浏览器,你就可以像这样轻松地做到这一点: