Javascript 将 JS 对象转换为 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4162749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 11:10:26  来源:igfitidea点击:

Convert JS object to JSON string

javascriptjsonstringobject

提问by Bin Chen

If I defined an object in JS with:

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

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

How can I convert the object to JSON? The output string should be:

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

'{"name":"binchen"}'

回答by Andris

All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:

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

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

回答by Ignacio Vazquez-Abrams

With JSON.stringify()found in json2.jsor native in most modern browsers.

随着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.

       This method produces a JSON text from a JavaScript value.
   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.

       This method produces a JSON text from a JavaScript value.

回答by Sarfraz

Check out updated/better way by Thomas Frank:

查看 Thomas Frank 更新/更好的方式:

Update May 17, 2008: Small sanitizer added to the toObject-method. Now toObject() will not eval() the string if it finds any malicious code in it.For even more security: Don't set the includeFunctions flag to true.

Douglas Crockford, father of the JSON concept, wrote one of the first stringifiers for JavaScript. Later Steve Yen at Trim Path wrote a nice improved version which I have used for some time. It's my changes to Steve's version that I'd like to share with you. Basically they stemmed from my wish to make the stringifier:

  • handle and restore cyclical references
  • include the JavaScript code for functions/methods (as an option)
  • exclude object members from Object.prototype if needed.

2008 年 5 月 17 日更新:向 toObject 方法添加了小型消毒剂。现在,如果 toObject() 在字符串中发现任何恶意代码,则它不会 eval() 字符串。为了更加安全:不要将 includeFunctions 标志设置为 true。

道格拉斯·克罗克福德 (Douglas Crockford) 是 JSON 概念之父,他为 JavaScript 编写了最早的字符串化符之一。后来,Trim Path 的 Steve Yen 写了一个很好的改进版本,我已经使用了一段时间。我想与您分享的是我对 Steve 版本的更改。基本上,它们源于我制作字符串化器的愿望:

  • 处理和恢复循环引用
  • 包括函数/方法的 JavaScript 代码(作为选项)
  • 如果需要,从 Object.prototype 中排除对象成员。

回答by Aravindan Venkatesan

You can use JSON.stringify()method to convert JSON object to String.

您可以使用JSON.stringify()方法将 JSON 对象转换为 String。

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

For reverse process, you can use JSON.parse()method to convert JSON String to JSON Object.

对于反向过程,您可以使用JSON.parse()方法将 JSON 字符串转换为 JSON 对象。

回答by Nazrul Islam

In angularJS

在 angularJS 中

angular.toJson(obj, pretty);

obj: Input to be serialized into JSON.

obj:要序列化为 JSON 的输入。

pretty(optional):
If set to true, the JSON output will contain newlines and whitespace. If set to an integer, the JSON output will contain that many spaces per indentation.

漂亮(可选):
如果设置为 true,JSON 输出将包含换行符和空格。如果设置为整数,JSON 输出将包含每个缩进的多个空格。

(default: 2)

(默认:2)

回答by Vignesh Murugan

JSON.stringify(j, null, 4)would give you beautified JSON in case you need beautification also

JSON.stringify(j, null, 4)如果您还需要美化,会给您美化的 JSON

The second parameter is replacer. It can be used as Filter where you can filter out certain key values when stringifying. If set to null it will return all key value pairs

第二个参数是replacer。它可以用作过滤器,您可以在字符串化时过滤掉某些键值。如果设置为 null 它将返回所有键值对

回答by Ariel Cabib

If you're using AngularJS, the 'json' filter should do it:

如果您使用的是 AngularJS,则 'json' 过滤器应该这样做:

<span>{{someObject | json}}</span>

回答by Dulith De Costa

JSON.stringifyturns a Javascript object into JSON text and stores that JSON text in a string.

JSON.stringify将 Javascript 对象转换为 JSON 文本并将该 JSON 文本存储在字符串中。

The conversion is an Object to String

转换是一个对象到字符串

JSON.parseturns a string of JSON text into a Javascript object.

JSON.parse将一串 JSON 文本转换为 Javascript 对象。

The conversion is a String to Object

转换是字符串到对象

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

to make it a JSON String following could be used.

使其成为可以使用的 JSON 字符串。

JSON.stringify({"key":"value"});

JSON.stringify({"name":"binchen"});

For more info you can refer to this link below.

有关更多信息,您可以参考下面的此链接。

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

回答by Rohit Kumar

One custom defined for this , until we do strange from stringify method

为此定义了一个自定义,直到我们从 stringify 方法中执行了奇怪的操作

var j={"name":"binchen","class":"awesome"};
var dq='"';
var json="{";
var last=Object.keys(j).length;
var count=0;
for(x in j)
{
json += dq+x+dq+":"+dq+j[x]+dq;
count++;
if(count<last)
   json +=",";
}
json+="}";
document.write(json);

OUTPUT

输出

{"name":"binchen","class":"awesome"}

LIVEhttp://jsfiddle.net/mailmerohit5/y78zum6v/

直播http://jsfiddle.net/mailmerohit5/y78zum6v/

回答by Sam

I was having issues with stringify running out of memory and other solutions didnt seem to work (at least I couldn't get them to work) which is when I stumbled on this thread. Thanks to Rohit KumarI just iterate through my very large JSON object to stop it from crashing

我遇到了 stringify 内存不足的问题,其他解决方案似乎不起作用(至少我无法让它们工作),这是我偶然发现这个线程的时候。感谢Rohit Kumar我只是遍历我非常大的 JSON 对象来阻止它崩溃

var j = MyObject;
var myObjectStringify = "{\"MyObject\":[";
var last = j.length
var count = 0;
for (x in j) {
    MyObjectStringify += JSON.stringify(j[x]);
    count++;
    if (count < last)
        MyObjectStringify += ",";
}
MyObjectStringify += "]}";

MyObjectStringify would give you your string representaion (just as mentioned other times in this thread) except if you have a large object, this should also work - just make sure you build it to fit your needs- I needed it to have a name than array

MyObjectStringify 会给你你的字符串表示(就像在这个线程中其他时候提到的那样),除非你有一个大对象,这也应该有效——只要确保你构建它满足你的需要——我需要它的名字而不是数组