2010-07-07 24 views
3
{"some_id": 
    [ 
    {"city":"Bellevue"}, 
    {"state":"Washington"} 
    ] 
} 
+11

“开放大括号,报价,一些ID,结肠,开方括号,敞开胸罩报价,报价,市场,报价,冒号,报价,贝尔视图,关闭大括号,逗号,打开大括号,报价,状态,报价,冒号,报价,华盛顿,报价,关闭大括号,关闭方括号,关闭大括号“。 :D – Russell 2010-07-07 00:47:35

+0

请参阅[替代JavaScript eval()解析JSON](http://stackoverflow.com/questions/945015/alternatives-to-javascript-eval-for-parsing-json)和[安全地将JSON字符串转换为一个对象](http://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object)一些方法 – 2010-07-07 00:48:58

+0

@Russel haha​​ha。 – DanC 2010-07-07 00:49:01

回答

3
var json = {"some_id": [ {"city":"Bellevue"}, {"state":"Washington"} ] } 

json.some_id[0].city等于 “贝尔维尤”

json.some_id[1].state等于 “华盛顿”

5
var theJSonString = '({"some_id": [ {"city":"Bellevue"}, {"state":"Washington"} ] })'; 
var x = eval(theJSonString); 
alert(x.some_id[0].city); // will display "Bellevue" 
+1

如果你用'eval'解析JSON,你需要将内容包装在圆括号中(例如'eval('('+ theString +')')'),否则它会被解析为一个块语句,而不是一个对象文字。 – 2010-07-07 02:02:05

+0

添加缺少的括号。谢谢@Matthew Crumley – DanC 2010-07-07 03:10:03

0

A目前的浏览器支持window.JSON.parse()。它采用JSON格式的字符串并返回一个Javascript对象或数组。

演示:http://jsfiddle.net/ThinkingStiff/KnbAJ/

脚本:

var json = '{"some_id":[{"city":"Bellevue"},{"state":"Washington"}]}' 
    object = window.JSON.parse(json); 

document.getElementById('length').textContent = object.some_id.length; 
document.getElementById('city').textContent = object.some_id[0].city; 
document.getElementById('state').textContent = object.some_id[1].state; 

HTML:

length: <span id="length"></span><br /> 
some_id[0].city: <span id="city"></span><br /> 
some_id[1].state: <span id="state"></span><br /> 

输出:

length: 2 
some_id[0].city: Bellevue 
some_id[1].state: Washington