使用JQuery将JSON对象解析为数组

时间:2017-07-21 02:00:41

标签: jquery arrays json

来自WEB API的结果     在调用Web API之后,我能够获得以下JSON格式(来自Telerik Fiddler的结果)。

[
   {
      "modelEmployeeID": 1,
      "modelFirstName": "Mike",
      "modelLastName": "Tai",
      "modelBirthDate": "1900-01-01T00:00:00",
      "modelPosition": "IT Exec",
      "modelHireDate": "2017-01-01T00:00:00",
      "modelStateID": 1
   },
   {
      "modelEmployeeID": 2,
      "modelFirstName": "Sue",
      "modelLastName": "Yoong",
      "modelBirthDate": "1990-07-16T00:00:00",
      "modelPosition": "IT Manager",
      "modelHireDate": "2017-02-28T00:00:00",
      "modelStateID": 2
   }
]

JQUERY

**And I am calling the API using JQuery with the following method:**

var dbImpl = {
    load: function (loadOptions) {
       return $.getJSON('http://localhost:777/employee/testjson');
    },
};

预期结果     我希望结果有多个对象数组:(我希望结果标记为“1”,目前结果标记为“2”)

enter image description here

2 个答案:

答案 0 :(得分:0)

您似乎希望$.getJSON()同步返回JSON。它不像那样工作,它是异步的(它只是uses Ajax internally)。我当然不确定我知道你真正想要的是什么,但你肯定会这样做吗?

var dbImpl;
$.getJSON('http://localhost:777/employee/testjson', function(result) {
    dbImpl = result;
});

所有这一切都是使用getJSON来检索JSON,然后将其分配给成功函数中的dbImpl。假设数据与您在问题中显示的数据相同,那么dbImpl将在您问题的#1屏幕截图中显示为statestest

答案 1 :(得分:0)

尝试Array.map()方法

var statestest = jsonObj.map(item => [item]);

工作演示



var jsonObj = [
   {
      "modelEmployeeID": 1,
      "modelFirstName": "Mike",
      "modelLastName": "Tai",
      "modelBirthDate": "1900-01-01T00:00:00",
      "modelPosition": "IT Exec",
      "modelHireDate": "2017-01-01T00:00:00",
      "modelStateID": 1
   },
   {
      "modelEmployeeID": 2,
      "modelFirstName": "Sue",
      "modelLastName": "Yoong",
      "modelBirthDate": "1990-07-16T00:00:00",
      "modelPosition": "IT Manager",
      "modelHireDate": "2017-02-28T00:00:00",
      "modelStateID": 2
   }
];

var statestest = jsonObj.map(item => [item]);

console.log("statestest", statestest);