基本的Json / javascript查询

时间:2012-05-23 11:06:33

标签: javascript json

嗨,我是json的新手。我正在尝试将json文件解析成一个网页,就像在这个帖子中解释的那样.........

Very basic JSON question

但是我的json文件是一个很大的联系人列表,它们不在上面例子中的'people'之类的数组中。相反,我的json文件的前6行如下所示。

{ "first_name": "Tom", "last_name": "Moore", "phone": "123456", "email": "tom@abc.ie" }
{ "first_name": "Fred", "last_name": "Power", "phone": "197412", "email": "fred@abc.ie" }
{ "first_name": "Ann", "last_name": "Doyle", "phone": "836547", "email": "ann@abc.ie" }
{ "first_name": "Phil", "last_name": "Jones", "phone": "927481", "email": "phil@abc.ie" }
{ "first_name": "Jane", "last_name": "Ross", "phone": "993377", "email": "jane@abc.ie" }
{ "first_name": "Tom", "last_name": "Moore", "phone": "123456", "email": "tom@abc.ie" }

如何在上面的线程中循环显示它们?非常感谢提前。

4 个答案:

答案 0 :(得分:1)

你的json无效。它需要外部的方括号和项目之间的逗号。它应该是:

[
    { "first_name": "Tom", "last_name": "Moore", "phone": "123456", "email": "tom@abc.ie" },
    { "first_name": "Fred", "last_name": "Power", "phone": "197412", "email": "fred@abc.ie" },
    { "first_name": "Ann", "last_name": "Doyle", "phone": "836547", "email": "ann@abc.ie" },
    { "first_name": "Phil", "last_name": "Jones", "phone": "927481", "email": "phil@abc.ie" },
    { "first_name": "Jane", "last_name": "Ross", "phone": "993377", "email": "jane@abc.ie" },
    { "first_name": "Tom", "last_name": "Moore", "phone": "123456", "email": "tom@abc.ie" }
]

$.getJSON为你处理json解析 - 只需执行:

$.getJSON('/url/of/the/json/file', function(people) {
    alert(people[0].first_name)
});

答案 1 :(得分:0)

这不是json格式,所以你将无法使用json的函数来处理它。我建议在服务器端使用lib / function来创建正确的json输出,然后在客户端使用它也会容易得多。

答案 2 :(得分:0)

var t = eval('[{ "first_name": "Tom", "last_name": "Moore", "phone": "123456", "email": "tom@abc.ie" },{ "first_name": "Fred", "last_name": "Power", "phone": "197412", "email": "fred@abc.ie" },{ "first_name": "Ann", "last_name": "Doyle", "phone": "836547", "email": "ann@abc.ie" },{ "first_name": "Phil", "last_name": "Jones", "phone": "927481", "email": "phil@abc.ie" },{ "first_name": "Jane", "last_name": "Ross", "phone": "993377", "email": "jane@abc.ie" },{ "first_name": "Tom", "last_name": "Moore", "phone": "123456", "email": "tom@abc.ie" }]');

for (i in t) {
var data = t[i];
  for (k in data) {
    alert(k+" >> "+data[k])
  }
}

你可以得到" k"作为关键和"数据[k]"作为价值。

答案 3 :(得分:0)

如前所述,您的JSON无效,如果有疑问,您可以随时查看:

http://jsonlint.com/ 要么 http://json.parser.online.fr/