【问题标题】:getJSON to fetch data from this json arraygetJSON 从这个 json 数组中获取数据
【发布时间】:2012-02-02 00:21:51
【问题描述】:

这是我的代码中的一个示例 json 数组。如何使用 getJSON 从这个数组中获取数据。

"Restoration": [
                {
                "Easy": {
                "value": "1",
                "info": "This is Easy."
                },
                "Medium": {
                "value": ".75",
                "info": "This is Medium."
                },
                "Difficult": {
                "value": ".5",
                "info": "This is Difficult."
                }
                }
                ]

【问题讨论】:

标签: javascript json jquery getjson


【解决方案1】:

使用 jQuery jQuery.getJSON():

 $.getJSON('ajax/test.json', function(data) {
     console.log(data); //see your data ( works in Chrome / FF with firebug)
     console.log(data["Restoration"][0]["easy"]["value"]) //should output 1
 });

【讨论】:

    【解决方案2】:

    这是使用 "jQuery.getJSON()" 的替代方法,因为有时我们没有 "domain/file.json" 或其他地方来执行 $get,或者我们没有想用jQuery 对于这个简单的过程。

    此方法从字符串中解析json

    你可以像这样使用简单的 javascript 来做到这一点:

    //json string for testing
    var jsonstr = '{"id":"743222825", "name":"Oscar Jara"}';
    
    //parse json
    var data = JSON.parse(jsonstr);
    
    //print in console
    console.log("My name is: " + data.name + " and my id is: " + data.id);
    

    希望这会有所帮助。

    问候。

    【讨论】:

    • 您没有尝试自己运行代码,是吗? JSON.parse 抛出错误,因为您传递的值不是字符串。
    • @FelixKling 是的,你是对的,我错过了quotes,感谢您指出这一点(我已经更新了帖子)。
    • 哦,哇,我没有意识到这个问题来自 2012 年。抱歉,我会自己编辑答案,而不是留下半刻薄的评论:-/
    • @FelixKling 没问题,没关系。
    【解决方案3】:

    这可能会对你有所帮助。

    http://underscorejs.org/#keys

    var list=_.Keys(data["Restoration"][0]);
    

    【讨论】:

      猜你喜欢
      • 2014-02-22
      • 2013-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-16
      相关资源
      最近更新 更多