如何在 JavaScript 中创建 JSON 字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8963693/
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-24 08:13:15  来源:igfitidea点击:

How to create JSON string in JavaScript?

javascriptjson

提问by indianwebdevil

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?

在这样的代码中,我试图创建 JSON 字符串只是为了玩。这是抛出错误,但如果我将所有姓名、年龄、已婚都放在一行(第 2 行)中,则不会。有什么问题?

采纳答案by bardiir

Javascript doesn't handle Strings over multiple lines.

Javascript 不处理多行的字符串。

You will need to concatenate those:

您将需要连接这些:

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

You can also use template literals in ES6 and above: (See here for the documentation)

您还可以在 ES6 及更高版本中使用模板文字:(有关文档,请参见此处

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

回答by Akhil Sekharan

The way i do it is:

我这样做的方式是:

   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.

我想这种方式可以减少出错的机会。

回答by Didier Ghys

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

函数 JSON.stringify 会将您的 json 对象转换为字符串:

var jsonAsString = JSON.stringify(obj);

In case the browser does not implement it (IE6/IE7), use the JSON2.jsscript. It's safe as it uses the native implementation if it exists.

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

回答by Hidden

This can be pretty easy and simple

这可能非常容易和简单

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.

回答by TimWolla

Use JSON.stringify:

使用JSON.stringify

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

回答by SULFIKAR A N

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);

回答by powtac

There is a "official" JSON implementation http://www.json.org/js.htmlby Crockford: https://github.com/douglascrockford/JSON-js

有一个“官方” JSON实施http://www.json.org/js.html由克罗克福德:https://github.com/douglascrockford/JSON-js

回答by Marc B

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

json 字符串中不能有换行符。你必须把它全部写成一行:{"key":"val","key2":"val2",etc....}.

But don't generate JSON strings yourself. There's plenty of libraries that do it for you, the biggest of which is jquery.

但不要自己生成 JSON 字符串。有很多库可以为您做这件事,其中最大的是jquery