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

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

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

'{"name":"binchen"}'

当前回答

如果你使用的是AngularJS, 'json'过滤器可以做到:

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

其他回答

要在Node JS中进行调试,可以使用util.inspect()。使用循环引用效果更好。

var util = require('util');
var j = {name: "binchen"};
console.log(util.inspect(j));

这是自定义的,直到我们使用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);

输出

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

住http://jsfiddle.net/mailmerohit5/y78zum6v/

使用本机函数JSON.stringify()

let userJson = {
name : 'Richard'
}
let userJsonString = JSON.stringify(userJson)
So in order to convert a js object to JSON String: 

将对象转换为字符串的简单语法是

JSON.stringify(value)

完整的语法是: JSON。Stringify (value[, replace [, space]])

让我们看一些简单的例子。注意,整个字符串得到 双引号,字符串中的所有数据都会转义 需要的。

JSON.stringify("foo bar"); // ""foo bar""
JSON.stringify(["foo", "bar"]); // "["foo","bar"]"
JSON.stringify({}); // '{}'
JSON.stringify({'foo':true, 'baz':false}); /* " 
{"foo":true,"baz":false}" */



const obj = { "property1":"value1", "property2":"value2"};
const JSON_response = JSON.stringify(obj);
console.log(JSON_response);/*"{ "property1":"value1", 
"property2":"value2"}"*/

如果你使用的是AngularJS, 'json'过滤器可以做到:

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