I have a JSON file with a JSON object I am attempting to read and edit using PHP but I wanted to change specific Key values which is proving to be abit of a problem. Would anyone have any pointers or links they may know that may help?
Thanks
I have a JSON file with a JSON object I am attempting to read and edit using PHP but I wanted to change specific Key values which is proving to be abit of a problem. Would anyone have any pointers or links they may know that may help?
Thanks
You can try this.
Firstly, decode your JSON:
$json_object = file_get_contents('some_file_name.json');
$data = json_decode($json_object, true);
Then edit what you want such as:
$data['some_key'] = "some_value";
Finally rewrite it back on the file (or a newer one):
$json_object = json_encode($data);
file_put_contents('some_file_name.json', $json_object);
Note: I assumed that the JSON comes from a file, but in place of that file system function you can very well use anything that returns a JSON object.
Transforming json to arrays and recursively updating keys (depth-nth)
function json_overwrite($json_original, $json_overwrite)
{
$original = json_decode($json_original, true);
$overwrite = json_decode($json_overwrite, true);
$original = array_overwrite($original, $overwrite);
return json_encode($original);
}
Recursively iterate and substitute $original
function array_overwrite(&$original, $overwrite)
{
// Not included in function signature so we can return silently if not an array
if (!is_array($overwrite)) {
return;
}
if (!is_array($original)) {
$original = $overwrite;
}
foreach($overwrite as $key => $value) {
if (array_key_exists($key, $original) && is_array($value)) {
array_overwrite($original[$key], $overwrite[$key]);
} else {
$original[$key] = $value;
}
}
return $original;
}
Quick test
$json1 = '{"hello": 1, "hello2": {"come": "here!", "you": 2} }';
$json2 = '{"hello": 2, "hello2": {"come": "here!", "you": 3} }';
var_dump(json_overwrite($json1, $json2));