亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何從外部URL重寫/重構JSON?

如何從外部URL重寫/重構JSON?

PHP
斯蒂芬大帝 2022-08-19 16:37:57
這個問題已經存在了很長時間,當我想到在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文件的正確方法。
查看完整描述

2 回答

?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

在循環中,您需要創建所需值的關聯數組,并將其推送到整體結果數組中。在循環結束時,輸出該數組的結果: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) {

    $item = array(

        "usuarioId" => $content->licitacaoId,

        "ano" => $content->anoProcesso,

        "entidadeId" => $content->unidade->orgao->ente->enteId,

        "nome" => $content->unidade->orgao->ente->nome

    );

    $output[] = $item;

echo json_encode($output);


查看完整回答
反對 回復 2022-08-19
?
眼眸繁星

TA貢獻1873條經驗 獲得超9個贊

創建一個包含所需內容的新數組并調用 。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) {

    return ["usuarioId" => $itemdoc->userId,

            "ano" => $itemdoc->year,

            "entidadeId" => $itemdoc->unity->organ->entity->entityId,

            "nome" => $itemdoc->unity->organ->entity->name];

}, $objdoc->content);

echo json_encode($newdoc);


查看完整回答
反對 回復 2022-08-19
  • 2 回答
  • 0 關注
  • 91 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號