【发布时间】:2021-10-13 13:04:12
【问题描述】:
我正在努力解决这个问题。它不应该这么难。我显然错过了一步。
我从 openaq.org 提取数据
我返回的对象是基于 JSON 对象的。
现在,我正在使用 jQuery 来解析对象,我正在获取对象的子部分,其中包含我想要的特定参数,但我无法获取特定的键值对。
对象不会一直以相同的顺序返回。所以当我试图最初设置我的电话时,我做了类似的事情
obj.results.measurements[0].
好吧,既然 obj 可以按随机顺序返回,我又回去寻找 key,value 对,但它是错误的值,让我失去了视觉。
也就是说,我查看了use jQuery's find() on JSON object,但由于某种原因无法从 openaq.org 提供的对象中得到我需要的东西。
对象的一个版本如下所示:
{"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}
我正在尝试获取“pm25”值。
我试过的代码是这样的:
function getAirQualityJson(){
$.ajax({
url: 'https://api.openaq.org/v2/latest?coordinates=39.73915,-104.9847',
type: 'GET',
dataType: "json"
// data: data ,
}).done(function(json){
console.log("the json is" + JSON.stringify(json));
console.log("the json internal is" + JSON.stringify(json.results));
var obj = json.results;
var pm25 = "";
//console.log(JSON.stringify(json.results.measurements[0]["parameter"]));
$.each(json.results[0], function(i,items){
//console.log("obj item:" + JSON.stringify(obj[0].measurements));
$.each(obj[0].measurements, function(y,things){
//console.log("each measurement:" + JSON.stringify(obj[0].measurements[0].value));//get each measurement
//pm 2.5
//Can come back in random order, get value from the key "pm25"
// pm25 = JSON.stringify(obj[0].measurements[2].value);
pm25 = JSON.stringify(obj[0].measurements[0].value);
console.log("pm25 is: " + pm25); // not right
});
});
//Trying Grep and map below too. Not working
jQuery.map(obj, function(objThing)
{ console.log("map it 1:" + JSON.stringify(objThing.measurements.parameter));
if(objThing.measurements.parameter === "pm25"){
// return objThing; // or return obj.name, whatever.
console.log("map it:" + objThing);
}else{
console.log("in else for pm25 map");
}
});
jQuery.grep(obj, function(otherObj) {
//return otherObj.parameter === "pm25";
console.log("Grep it" + otherObj.measurements.parameter === "pm25");
});
});
}
getAirQualityJson();
https://jsfiddle.net/7quL0asz/
循环通过 I 运行,如您所见,我尝试了 [2],这是 'pm25' 值的原始位置,但随后将其位置切换到第三或第四位置,因此无法预测。
我尝试了 jQuery Grep 和 Map,但它返回 undefined 或 false。
所以我的问题是,我将如何解析它以获取“pm25”键值。之后,如果需要,我可以得到其余的。
提前感谢您的所有帮助。
【问题讨论】:
-
查看谁在树中遍历嵌套对象。
标签: javascript jquery json