Okky
Okky

Reputation: 10466

JSONarray without array name?

I have a Json file

{
   "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"
      }
   ]
}

And I take data from it using 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);
    }
});

Note: myFile attribute gives the name of JSON file

and append data to DOM

Can i Use a JSON like

{
   [
      {
         "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"
      }
   ]
}

If so how to call it?

Upvotes: 2

Views: 4339

Answers (1)

jgillich
jgillich

Reputation: 76319

Use JSONLint or JSLint to see if your syntax is correct, and you will get this:

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

While it may be possible to parse it anyway, you should never ever do this.

As noted by Marco S. in the comments, you can instead use this:

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

And access it like

result[0]["Name"]

Upvotes: 5

Related Questions