【问题标题】:JSONarray without array name?没有数组名称的JSONarray?
【发布时间】:2013-04-04 12:35:36
【问题描述】:

我有一个 Json 文件

{
   "info":[
      {
         "Name":"Noob Here1",
         "Department":"Language",
         "Sex":"Male",
         "Basic_Salary":"175",
         "ESI":"58",
         "Employee_PF":"60.50",
         "Bonus":"2.60"
      },
      {
         "Name":"Noob Here2",
         "Department":"Employee_PF",
         "Sex":"Female",
         "Basic_Salary":"10.5",
         "ESI":"4.0",
         "Employee_PF":"20",
         "Bonus":"0.5"
      },
      {
         "Name":"Noob Here3",
         "Department":"Physics",
         "Sex":"Male",
         "Basic_Salary":"165",
         "ESI":"55",
         "Employee_PF":"875",
         "Bonus":"200"
      }
   ]
}

我使用 getJson 从中获取数据

loadData(myFile).done(function (data1) {

    // check if we acutally get something back and if the data has the info property
    if (data1 && data1.info) {
        data = data1;
        var html = "";
        var head = "";
        $.each(data1.info[0], function (key, value) {
            html += "<td><input data-bind='value:" + key + "'></td>";
            head += "<th>" + key + "</th>";
        });
        html += "<td><input data-bind='value: result'/></td>";
        head += "<th>Result</th>";
        $("#div1 thead").append(head);
        $("#div1").append("<tr></tr>");
        $("#div1 tr").append(html);
    }
});

注意:myFile 属性给出 JSON 文件的名称

并将数据附加到 DOM

我可以使用 JSON 之类的吗

{
   [
      {
         "Name":"Noob Here1",
         "Department":"Language",
         "Sex":"Male",
         "Basic_Salary":"175",
         "ESI":"58",
         "Employee_PF":"60.50",
         "Bonus":"2.60"
      },
      {
         "Name":"Noob Here2",
         "Department":"Employee_PF",
         "Sex":"Female",
         "Basic_Salary":"10.5",
         "ESI":"4.0",
         "Employee_PF":"20",
         "Bonus":"0.5"
      },
      {
         "Name":"Noob Here3",
         "Department":"Physics",
         "Sex":"Male",
         "Basic_Salary":"165",
         "ESI":"55",
         "Employee_PF":"875",
         "Bonus":"200"
      }
   ]
}

如果是怎么调用呢?

【问题讨论】:

  • data1[0][0] 在这里给菜鸟1
  • 删除 .info 并按原样处理数据
  • 可以使用 for 语句循环遍历数组
  • 第二个 JSON 示例无效,因为必须命名对象元素。

标签: javascript jquery json getjson


【解决方案1】:

使用JSONLintJSLint 看看你的语法是否正确,你会得到这个:

Parse error on line 1:
{    [        {        
-----^
Expecting 'STRING', '}'

虽然无论如何都可以解析它,但你永远不应该这样做。

正如 Marco S. 在 cmets 中所指出的,您可以改用 this

[
    {
         "Name":"Noob Here1",
         "Department":"Language",
         "Sex":"Male",
         "Basic_Salary":"175",
         "ESI":"58",
         "Employee_PF":"60.50",
         "Bonus":"2.60"
     },
     ...
]

然后像访问它

result[0]["Name"]

【讨论】:

    猜你喜欢
    • 2012-04-27
    • 2016-12-17
    • 2021-05-27
    • 2015-09-20
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 2020-01-08
    • 1970-01-01
    相关资源
    最近更新 更多