I am working on a shopware project that requires me setup a json of all orders that is processed.
the json is stored in a directory which I have gotten out and passed to a variable fil.
$filer = $order1->getOrderNumber() . '_' . $country2->getIso() . '.json';
$fil = __DIR__ . '/' . $filer;
$file_contents = file_get_contents($fil);
The gotten json stored in variable fil is then passed to variable jsonData
$jsonData = $fil;
I am trying to replace the value of a key as below by decoding the json into an array
$data = json_decode($jsonData, true);
The key to be replaced is as below (trying to replace ID)
$data['entity']['payments'][0]['state']['id'] = $logMessageId;
I then try to save it back in variable modifiedJsonData and replace back to directory
$modifiedJsonData = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents($fil, $modifiedJsonData);
it seemed to work partially but not fully, instead of replacing the (ID) alone
as here : $data['entity']['payments'][0]['state']['id']
its replaces all the content of the json as below, the json content is supposed to be more than the below:
{
"entity": {
"payments": [
{
"state": {
"id": #####
}
}
]
}
}
Please help, what could I be doing wrong
2
Answers
I was also able to find away around it by:
Use JSON_THROW_ON_ERROR with json_decode():
or below PHP 8:
(since PHP 7.3)