【问题标题】:Complex JSON obj and jQuery or Javascript map to specific key, value复杂的 JSON obj 和 jQuery 或 Javascript 映射到特定的键、值
【发布时间】: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


【解决方案1】:

您可以使用array#findoptional chaining 来执行此操作,

因为我们使用的是optional chaining,所以如果缺少属性,将返回undefined

演示:

let data = {"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³"}]}]}

let found = data?.results?.[0]?.measurements?.find?.(
    ({ parameter }) => parameter === "pm25"
);

console.log(found);

【讨论】:

  • 这是什么美丽的巫术。太棒了!这将如何处理参数返回为空。就像“pm25”不在对象中一样?
  • @ClosDesign 如果pm25 不在任何对象中,found 将被设置为 undefined 而不是抛出错误。
【解决方案2】:

您可以遍历measurements 并找到您需要的对象:

const data = '{"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³"}]}]}';
const json = JSON.parse(data);
let value = null;

const measurements = json?.results?.[0]?.measurements ?? null;
if(measurements) 
  for (const item of measurements) 
    if (item.parameter === 'pm25') {
      value = item.value;
      break;
    }

if (value) {
  // here you can use the value
  console.log(value);
}
else {
  // here you should handle the case where 'pm25' is not found
}

【讨论】:

  • 使用这个解决方案,它可以满足我的需求。我确实喜欢看到 if/else 处理。
猜你喜欢
  • 2021-08-15
  • 1970-01-01
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-27
相关资源
最近更新 更多