【问题标题】:Retrive Json Data, reformat it and create new endpoint检索 Json 数据,重新格式化并创建新端点
【发布时间】:2018-08-26 19:40:12
【问题描述】:

British Air quality 等公共 api 获取一些 Json 数据的最佳方法是什么,即使用不同名称的一些数据创建一个新端点,例如

{ 
  "data":[{ 
    "from": "2018-03-17T22:00Z",
    "to": "2018-03-17T22:30Z",
    "intensity": {
      "forecast": 251,
      "actual": 250,
      "index": "moderate"
    }
  }]
}

为此(我正在删除一些我不需要的信息)

{
"Weather": [
   {"newName": "forecastValue"},
   {"newName2": "ActualValue"}
 ]
}

我正面临这个问题,因为我正在使用第三方应用程序,该应用程序仅支持 Json 格式(2 个值和特殊名称)...

非常感谢您的任何帮助!

【问题讨论】:

  • 将 JSON 解码为数组 -> 重新格式化 -> 将其编码回 JSON -> 瞧!
  • @MehdiBounya 谢谢你的回答,我有这样的想法......所以我会暂时用 PHP 保存它并创建一个端点
  • 我知道这可能有点矫枉过正,但GraphQL 处理得很好。

标签: javascript php json rest web


【解决方案1】:

JavaScript 中的解决方案:

var orginalJSON = { 
  "data":[{ 
    "from": "2018-03-17T22:00Z",
    "to": "2018-03-17T22:30Z",
    "intensity": {
      "forecast": 251,
      "actual": 250,
      "index": "moderate"
    }
  }]
};

var newJSON = {
"Weather": [
   {"newName": orginalJSON.data[0].intensity.forecast},
   {"newName2": orginalJSON.data[0].intensity.actual}
 ]
};

console.log(newJSON);

【讨论】:

    【解决方案2】:

    这给出了一个稍微不同的 json 字符串作为输出,但我会说它比你的建议更有用

    <?php
    $in = '{
      "data":[{
        "from": "2018-03-17T22:00Z",
        "to": "2018-03-17T22:30Z",
        "intensity": {
          "forecast": 251,
          "actual": 250,
          "index": "moderate"
        }
      }]
    }';
    
    $jin = json_decode($in);
    
    $out = [];
    
    $out = new stdClass();
    $out->weather = ['newName'=>$jin->data[0]->intensity->forecast,
                     'newName2' =>$jin->data[0]->intensity->actual
                    ];
    $out = json_encode($out);
    
    echo $out;
    

    结果

    {"weather":{"newName":251,"newName2":250}}
    

    【讨论】:

      【解决方案3】:

      假设 a) 您在问题上放置的 JavaScript 标记意味着您希望在 JavaScript 中使用它,并且 b) 您的 JSON 在名为 jsonData 的变量中...

      var dataObj = JSON.parse(jsonData);
      var intensityData = dataObj.data[0].intensity;
      var outputData = {forecast: intensityData.forecast, actual: intensityData.actual};
      var jsonOutput = JSON.stringify(outputData);
      

      【讨论】:

        猜你喜欢
        • 2021-06-13
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        • 1970-01-01
        • 2019-08-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多