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

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

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

'{"name":"binchen"}'

当前回答

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>

非常容易使用的方法,但不要在发布版中使用它(因为可能存在兼容性问题)。

非常适合在您这边进行测试。

Object.prototype.toSource()

//Usage:
obj.toSource();

只使用JSON。Stringify来做这样的转换-但是记住,具有未定义值的字段将不会包含在json中

var j={“name”:“binchen”, “remember”:undefined, “age”: null }; var s=JSON.stringify(j); 控制台.log(s);

记住输出json中的“消失”字段

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"}"*/

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