0

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

非常基本的 JSON 问题

但是,我的 json 文件是一大堆联系人,这些联系人不在上面示例中的“人”之类的数组中。相反,我的 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

4 回答 4

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)
});
于 2012-05-23T11:09:07.330 回答
0

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

于 2012-05-23T11:09:45.997 回答
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”作为键,将“data[k]”作为值。

于 2012-05-23T11:13:03.443 回答
0

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

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

于 2012-05-23T12:00:01.720 回答