jQuery 将字符串转换为 JSON 对象

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

Convert string to JSON Object

jqueryjson

提问by jith10

How do I convert string to object? I am facing this problem because I am trying to read the elements in the JSON string using "each".

如何将字符串转换为对象?我面临这个问题是因为我试图使用“each”读取 JSON 字符串中的元素。

My string is given below.

我的字符串如下。

jsonObj = "{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"

I have used evaland I have used

我用过eval,我用过

var obj = $.parseJSON(jsonObj);

And i have also used

我也用过

var obj= eval("(" + jsonObj + ")");

But it comes null all the time

但它一直为空

回答by ShankarSangoli

Enclose the string in single quote it should work. Try this.

将字符串用单引号括起来,它应该可以工作。尝试这个。

var jsonObj = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var obj = $.parseJSON(jsonObj);

Demo

演示

回答by Arnold

Combining Saurabh Chandra Patel's answerwith Molecular Man's observation, you should have something like this:

结合Saurabh Chandra Patel回答Molecular Man观察,你应该有这样的东西:

JSON.parse('{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}');

回答by Mark Schultheiss

try:

尝试:

var myjson = '{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}';
var newJ= $.parseJSON(myjson);
    alert(newJ.TeamList[0].teamname);

回答by Saurabh Chandra Patel

only with js

只用js

   JSON.parse(jsonObj);

reference

参考

回答by Molecular Man

Your string is not valid. Double quots cannot be inside double quotes. You should escape them:

您的字符串无效。双引号不能在双引号内。你应该逃避他们:

"{\"TeamList\" : [{\"teamid\" : \"1\",\"teamname\" : \"Barcelona\"}]}"

or use single quotes and double quotes

或使用单引号和双引号

'{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}'

回答by Simon Edstr?m

Quick answer, this eval work:

快速回答,这个评估工作:

eval('var obj = {"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}')

回答by Chad

Without eval:

没有评估:

Your original string was not an actual string.

您的原始字符串不是实际字符串。

jsonObj = "{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"

The easiest way to to wrap it all with a single quote.

用单引号将其全部包装起来的最简单方法。

 jsonObj = '"{"TeamList" : [{"teamid" : "1","teamname" : "Barcelona"}]}"'

Then you can combine two steps to parse it to JSON:

然后可以结合两步解析成JSON:

 $.parseJSON(jsonObj.slice(1,-1))