How to create JSON string in JavaScript?

window.onload = function(){
var obj = '{
"name" : "Raj",
"age"  : 32,
"married" : false
}';


var val = eval('(' + obj + ')');
alert( "name : " + val.name + "\n" +
"age  : " + val.age  + "\n" +
"married : " + val.married );


}

In a code something like this, I am trying to create JSON string just to play around. It's throwing error, but if I put all the name, age, married in one single line (line 2) it doesn't. Whats the problem?

335638 次浏览

使用 JSON.stringify:

> JSON.stringify({ asd: 'bla' });
'{"asd":"bla"}'

json strings can't have line breaks in them. You'd have to make it all one line: {"key":"val","key2":"val2",etc....}.

但是不要自己生成 JSON 字符串。有很多库可以为您提供这种服务,其中最大的是 Jquery

免责声明: 对于如何在 JavaScript 中创建 JSON 的最佳方法,这不是一个可以遵循的答案。这个答案主要解决了“问题是什么?”这个问题或者为什么上面的代码不能工作-这是一个错误的字符串连接尝试在 JavaScript 中,并没有解决为什么字符串连接是一个非常糟糕的方式创建一个 JSON 字符串放在首位。

See here for best way to create JSON: https://stackoverflow.com/a/13488998/1127761

阅读这个答案可以理解为什么上面的代码示例不能工作。

Javascript 不能处理多行字符串。

你需要把这些连接起来:

var obj = '{'
+'"name" : "Raj",'
+'"age"  : 32,'
+'"married" : false'
+'}';

还可以在 ES6及以上版本中使用模板文字: (See here for the documentation)

var obj = `{
"name" : "Raj",
"age" : 32,
"married" : false,
}`;

The function JSON.stringify will turn your json object into a string:

var jsonAsString = JSON.stringify(obj);

如果浏览器没有实现它(IE6/IE7) ,使用 JSON2.js脚本。它是安全的,因为它使用本机实现(如果存在的话)。

我的方法是:

   var obj = new Object();
obj.name = "Raj";
obj.age  = 32;
obj.married = false;
var jsonString= JSON.stringify(obj);

I guess this way can reduce chances for errors.

I think this way helps you...

var name=[];
var age=[];
name.push('sulfikar');
age.push('24');
var ent={};
for(var i=0;i<name.length;i++)
{
ent.name=name[i];
ent.age=age[i];
}
JSON.Stringify(ent);

这很简单

var obj = new Object();
obj.name = "Raj";
obj.age = 32;
obj.married = false;


//convert object to json string
var string = JSON.stringify(obj);


//convert string to Json Object
console.log(JSON.parse(string)); // this is your requirement.