2

我有一个 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"
      }
   ]
}

如果有怎么称呼它?

4

1 回答 1

5

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

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

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

正如 Marco S. 在评论中指出的那样,您可以改用这个

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

并像访问它一样

result[0]["Name"]
于 2013-04-04T12:51:35.953 回答