过滤嵌套的API响应数据以输出JSON

eeq64g8w  于 2023-11-20  发布在  其他
关注(0)|答案(2)|浏览(144)

https://api.spacexdata.com/v3/launches/past上的一个API端点返回数据。我需要过滤该数据,以便在屏幕上显示一个JSON,该JSON只包含API数据条目,其中customers字段中包含“DARPA”,launch_year字段中包含“2017”。customerspayloads字段是任意长度的数组。
响应数据的第一个条目看起来像这样。它的一些字段被省略了。请访问API链接以查看完整的响应。

0   
  flight_number 1
  mission_name  "FalconSat"
  upcoming  false
  launch_year   "2006"
  launch_date_unix  1143239400
  launch_date_utc   "2006-03-24T22:30:00.000Z"
  launch_date_local "2006-03-25T10:30:00+12:00"
  is_tentative  false
  tentative_max_precision   "hour"
  tbd   false
  launch_window 0
  rocket    
    rocket_id   "falcon1"
    rocket_name "Falcon 1"
    rocket_type "Merlin A"
    first_stage {…}
    second_stage    
      block 1
      payloads  
        0   
          payload_id    "FalconSAT-2"
          norad_id  []
          reused    false
          customers 
            0   "DARPA"

字符串
我该怎么做?

sgtfey8w

sgtfey8w1#

给你

fetch('https://api.spacexdata.com/v3/launches/past')
  .then(res => res.json())
  .then(response => {
    const res = response.filter(
      x =>
        x.launch_year === '2007' && x.rocket.second_stage.payloads.some(payload => payload.customers.includes('DARPA'))
    );
    console.log(res);
  });

字符串

1szpjjfi

1szpjjfi2#

给你:

<?php
$data = json_decode(file_get_contents('https://api.spacexdata.com/v3/launches/past'), true);
foreach($data as $entry) {
   if($entry['launch_year'] === '2017') {
      if(isset($entry['rocket']['second_stage']['payloads'])) {
         foreach($entry['rocket']['second_stage']['payloads'] as $payload) {
            foreach($payload['customers'] as $customer) {
               if($customer === 'DARPA') print_r($entry);
            }
         }
      }
   }
}

字符串
你需要自己添加一些错误处理。代码可以工作,但2017年没有DARPA客户。如果你检查2006年,它会找到它。

相关问题