将 JS 对象转换为 JSON 字符串
2022-08-29 22:03:53
如果我在JS中定义了一个对象:
var j={"name":"binchen"};
如何将对象转换为 JSON?输出字符串应为:
'{"name":"binchen"}'
如果我在JS中定义了一个对象:
var j={"name":"binchen"};
如何将对象转换为 JSON?输出字符串应为:
'{"name":"binchen"}'
所有当前浏览器都内置了本机 JSON 支持。因此,只要您不处理像IE6 / 7这样的史前浏览器,您就可以像这样轻松地做到这一点:
var j = {
"name": "binchen"
};
console.log(JSON.stringify(j));
在 json2 中找到.js或在大多数现代浏览器中都是原生的。JSON.stringify()
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.