将 JS 对象转换为 JSON 字符串

新手上路,请多包涵

如果我在 JS 中定义了一个对象:

var j={"name":"binchen"};

如何将对象转换为 JSON?输出字符串应该是:

'{"name":"binchen"}'

原文由 Bin Chen 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 711
2 个回答

所有当前的浏览器都内置了原生 JSON 支持。所以只要你不处理像 IE6/7 这样的史前浏览器,你就可以像这样轻松地做到这一点:

 var j = {
 "name": "binchen"
 };
 console.log(JSON.stringify(j));

原文由 Andris 发布,翻译遵循 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 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题