猿问

如何从外部URL重写/重构JSON?

这个问题已经存在了很长时间,当我想到在StackOverflow这里问这个问题时。我在互联网上搜索了一个解决方案,但我没有成功。我没有找到任何主题。


问题是:是否可以重写(重构)现有的外部JSON文件?


想象一下,你想消除一些你不使用的对象,或者从一些API翻译对象,或者只是让它更干净。


示例 JSON 文件:


{

  "content" : [ {

    "userId" : 3370,

    "year" : 2015,

    "unity" : {

      "organ" : {

        "entity" : {

          "entityId" : 2102309,

          "name" : "Jack Sparrow"

        },

    "type" : null,

    "lic" : [ ]

  }],

  "numberOfElements" : 1,

  "totalPages" : 0,

  "totalElements" : 1,

  "firstPage" : true,

  "lastPage" : false,

  "size" : 0,

  "number" : 0

}

示例 - 输出 - JSON 文件 - 重组:(结果)


[

  {

    "userId": 3370,

    "year": 2015,

    "entityId": "2102309",

    "name": "Jack Sparrow"

  }

]

通过PHP进行这种重组的最有效方法是什么?


我在PHP中尝试了这样的东西:


<?php

$json_strdoc = file_get_contents("https://example.com/arquivojson"); //Get the file


    $objdoc = json_decode($json_strdoc); //Decoding JSON


   echo "["; //Beginning

        foreach ($objdoc as $itemdoc){  //Printing elements individually


            echo "


  {

    "usuarioId": $itemdoc->content->userId,

    "ano": $itemdoc->content->year,

    "entidadeId": $itemdoc->content->unity->organ->entity->entityId,

    "nome": $itemdoc->content->unity->organ->entity->name

  },

"

   echo "]"; //End


?>

我不是PHP的专家,所以我用一个我知道是错误的代码来举例说明,但这更容易理解。我还没有找到打印新JSON文件的正确方法。


斯蒂芬大帝
浏览 101回答 2
2回答

慕勒3428872

在循环中,您需要创建所需值的关联数组,并将其推送到整体结果数组中。在循环结束时,输出该数组的结果:json_encode$json_strdoc = file_get_contents("https://example.com/arquivojson"); //Get the file$objdoc = json_decode($json_strdoc); //Decoding JSON$output = array();foreach ($objdoc->content as $content) {&nbsp; &nbsp; $item = array(&nbsp; &nbsp; &nbsp; &nbsp; "usuarioId" => $content->licitacaoId,&nbsp; &nbsp; &nbsp; &nbsp; "ano" => $content->anoProcesso,&nbsp; &nbsp; &nbsp; &nbsp; "entidadeId" => $content->unidade->orgao->ente->enteId,&nbsp; &nbsp; &nbsp; &nbsp; "nome" => $content->unidade->orgao->ente->nome&nbsp; &nbsp; );&nbsp; &nbsp; $output[] = $item;}&nbsp;echo json_encode($output);

眼眸繁星

创建一个包含所需内容的新数组并调用 。json_encode()此外,数组位于 中,而不是 。你应该循环它,而不是在循环内部使用。$objdoc->content$objdoc$itemdoc->content<?php$json_strdoc = file_get_contents("https://example.com/arquivojson"); //Get the file$objdoc = json_decode($json_strdoc); //Decoding JSON$newdoc = array_map(function($itemdoc) {&nbsp; &nbsp; return ["usuarioId" => $itemdoc->userId,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "ano" => $itemdoc->year,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "entidadeId" => $itemdoc->unity->organ->entity->entityId,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "nome" => $itemdoc->unity->organ->entity->name];}, $objdoc->content);echo json_encode($newdoc);
随时随地看视频慕课网APP
我要回答