首页 > 解决方案 > 使用 jQuery/plain JS 从 JSON 文件中提取的正确方法是什么?

问题描述

解决了

原来我在尝试修复它时弄乱了我的 JSON。感谢您的帮助。向我展示了一些使用 json 的新方法 :)

我搜索了很多其他问题,尝试了答案,有些做了一些其他的事情,只是抛出了一个错误。如果有效,它会将整个元数据列表(包括我想要的 json 数据)记录到控制台:

{…}
​
abort: function abort(e)​
always: function always()​
catch: function catch(e)​
done: function add()​
fail: function add()​
getAllResponseHeaders: function getAllResponseHeaders()​
getResponseHeader: function getResponseHeader(e)​
overrideMimeType: function overrideMimeType(e)​
pipe: function pipe()​
progress: function add()​
promise: function promise(e)
​
readyState: 4
​
responseText: "<JSON content>"
​
setRequestHeader: function setRequestHeader(e, t)​
state: function state()
​
status: 200
​
statusCode: function statusCode(e)
​
statusText: "OK"
​
then: function then(t, n, r)​
<prototype>: Object { … }

所以,我的问题是:如何从中获取 json 内容?

使用的代码:

function start() {
  var j = $.ajax({
    url: 'users.json',
    type: "GET",
    dataType: "json",
    success: function (data) {
      console.log(data);
    }
  });
}

杰森:

        "UsersByID":[ {
                "id": 1
                "Name": ["K", "L", "Smiths"],
                "Birthday": ["03", "10", "1987"],
                "Username": "user1",
                "Password": "verysafepassword",
                "Hollidays": [{
                        "HollidayId": 1
                        "HollidayType": 2,
                        "AmountOfPeople": 5,
                        "Date": ["18", "08", "2020"]
                        }{
                        "HollidayId": 2
                        "HollidayType": 3,
                        "AmountOfPeople": 2,
                        "Date": ["24", "10", "2020"]
                        }

                }]

        }]
    }
}

标签: javascriptjqueryjson

解决方案


您通常做的(在纯 javascript 中)是通过传递的 JSON 进行过滤。由于我不知道您要过滤什么,一些伪代码是如何工作的:

   function start() {
     var j = $.ajax({
       url: 'users.json',
       type: "GET",
       dataType: "json",
       success: function (response) { //data is a keyword so better use response
         console.log(response);

        response.data.forEach(function(field) { // we iterate through each field in the JSON
         if (field.typeField == "UsersByID") {  // Given the JSON part looks like {"UsersByID":{"myBigData": "secrets","yourBigData": "noSecrets"}}
        console.info("My content found"); 
        // Do whatever you have to do with the content
        }
      }); // for each END

    }
  });
}

EDITT处理 JSON 有不同的可能性如果你知道正在发生什么,你可以像我上面所做的那样过滤,然后对结果做一些事情。
另一种方法,如果您不必提取,但整个响应是所需的 JSON,您可以执行以下操作(当然您可以组合)

function start() {
     var j = $.ajax({
       url: 'users.json',
       type: "GET",
       dataType: "json",
       success: function (response) { //data is a keyword so better use response
         console.log(response);
         var myObj = JSON.parse(response);
        // Do whatever you have to do with myObj e.g.
       var u_username = myObj.Username; // you retrieve from the object with the field names
  // when nested you get a new object and then you retrieve
    var objHollidays = myObj.Hollidays;
    var u_HollidayId = objHollidays.HollidayId;
    // OR you iterate over all objHollidays 
    objHollidays.HollidayId.forEach(function(field) { // we iterate through each 
        //Do whatever you need
       });
    }
  });
} 

解析日期
JSON 中不允许使用日期对象。
如果需要包含日期,请将其写为字符串。
您可以稍后将其转换回日期对象:

 var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
 var obj = JSON.parse(text);
 obj.birth = new Date(obj.birth);

推荐阅读