JSON从本地目录解析JQuery

时间:2013-08-08 16:55:05

标签: jquery json parsing

我在data / data.json

中的本地文件夹中有JSON数据
{"category":"Soups","menu_item":"Tomato Soup","type":"veg"},{"category":"Starters","menu_item":"Summer Salad","type":"veg"},{"category":"Main Course","menu_item":"Black Beans Chicken","type":"non-veg"},{"category":"Soups","menu_item":"Lentil Soup","type":"veg"},{"category":"Starters","menu_item":"Roasted Root Veg","type":"veg"},{"category":"Starters","menu_item":"Herbed Chicken Wings","type":"non-veg"},{"category":"Main Course","menu_item":"Barbecue Chicken Sandwich","type":"non-veg"},{"category":"Main Course","menu_item":"Pasta with Sausage","type":"veg"},{"category":"Starters","menu_item":"Roasted Shallot, Beet, Spinach","type":"non-veg"},{"category":"Starters","menu_item":"Sauteed Broccoli","type":"veg"},{"category":"Soups","menu_item":"Chicken Soup","type":"non-veg"}

我想读这个,我想获取数据,我正在尝试这个代码,但我没有得到任何东西......

$.getJSON("data/data.json",
    function (data) {
       var i;
       for (i=0; i<5; i++) {
          $('<a href="">  <b>ITEM : </b>' + data.items[i].category +'</a><br>').appendTo(document.body);
       }
});

3 个答案:

答案 0 :(得分:0)

JSON不正确。这似乎是一个对象数组,它们需要在括号之间包装:

不正确

{"category":"Soups","menu_item":"Tomato Soup","type":"veg"}, ... ,{"category":"Soups","menu_item":"Chicken Soup","type":"non-veg"}

CORRECT

[{"category":"Soups","menu_item":"Tomato Soup","type":"veg"}, ... ,{"category":"Soups","menu_item":"Chicken Soup","type":"non-veg"}]

答案 1 :(得分:0)

JavaScript无权访问本地文件系统。您必须设置一个可以为AJAX请求提供服务的Web服务器。您可以尝试使用Node.js(我从未使用它但可能有效),或使用LAMP / MAMP / WAMP设置(www.bitnami.com)

答案 2 :(得分:0)

主要是你的Json是无效的,如果它是一个对象数组,你应该将整个东西包含在[]中,如果它是一个带有嵌套对象的对象,你应该将它包含在内。

检查语法:http://json.org/

纠正后,您应该能够获取数据对象。