Home > Software design >  Dynamically update a nested JSON ( unknown level) using php
Dynamically update a nested JSON ( unknown level) using php

Time:06-18

I would like to update a json file using PHP

$Folder = $_REQUEST['Folder']; // "wwwroot/JSON/"
$File = $_REQUEST['File']; // "JSONOriginalFile.json"
$NewJSONValue = $_REQUEST['JsonValue']; // "NewValue"
$JsonObject = json_decode($_REQUEST['JsonObect']); // ["Layer1","Layer2","ObjectToUpdate"]
$JSON = file_get_contents($Folder.$File);
$JSON = json_decode($JSON);

The goal here is to run something dynamic that would do

$JSON->Layer1->Layer2->ObjectToUpdate = $NewJSONValue;
$JSON= json_encode($JSON);
file_put_contents('../../'.$Folder.'/'.$File, $JSON);

But i can't go in a dynamic nested layers ex: i could try with the same "app" to update ["Layer1","ObjectToUpdate"] or ["Layer1","Layer2","Layer3","ObjectToUpdate"] or simply ["ObjectToUpdate"] etc..

the goal is to have the array being transposed as nested search and the last array object the object to update.

is there something like this that exists within php?

even if run something like

$JsonString = "$JSON";
foreach($JsonObject as $Object) {
   $JsonString .= "->".$Object;
}

it does not help. anyone has a solution?

CodePudding user response:

You can use the curly brace syntax to access to the object method {$name_of method} ("like" you use the square brackets for arrays):

$str_json = '{"store":{"book":{"category":"reference","author":"Nigel Rees","title":"Sayings of the Century","price":8.95}}}';
$tag_to_edit = [ "store", "book", "author"];
$new_value = "A. Einstein";


$obj_json = json_decode($str_json);
$element_to_edit = $obj_json;

foreach($tag_to_edit as $t)
     $element_to_edit = &$element_to_edit->{$t};

$element_to_edit = $new_value;

die($obj_json->store->book->author); // A. Einstein

This will work.

  • Related