使用 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);
}
});
}

Json:

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

您通常所做的(在纯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);

最新更新