【问题标题】:Filter nested API response data to output json过滤嵌套的 API 响应数据以输出 json
【发布时间】:2023-03-04 17:35:02
【问题描述】:

https://api.spacexdata.com/v3/launches/past 的 API 端点返回数据。我需要过滤该数据以在屏幕上显示一个 json,该 json 将仅包含 customers 字段中带有“DARPA”的 API 数据条目和 launch_year 字段中带有“2017”的 API 数据条目。 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"

我该怎么做?

【问题讨论】:

    标签: json api fetch


    【解决方案1】:

    给你

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

    【讨论】:

      【解决方案2】:

      给你:

      <?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 年,它就会找到它。

      【讨论】:

      • 如果需要JSON格式的输出,只需将print_r($entry)改为echo json_encode($entry);
      • 代码看起来不错。你能把它重写成 JavaScript 吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      • 2021-06-03
      • 1970-01-01
      • 2019-02-12
      相关资源
      最近更新 更多