I'm working on a Shopware project and need to set up a JSON containing all processed orders.
This JSON is stored in a directory that I have found and passed to a variable $fil.
$filer = $order1->getOrderNumber() . '_' . $country2->getIso() . '.json'; $fil = __DIR__ . '/' . $filer; $file_contents = file_get_contents($fil);
The obtained JSON is stored in the variable $fil, and then passed to the variable $jsonData.
$jsonData = $fil;
I am trying to replace the value of the key below by decoding the JSON into an associative array.
$data = json_decode($jsonData, true);
The keys to be replaced are as follows (try replacing ID)
$data['entity']['payments'][0]['state']['id'] = $logMessageId;
Then I tried saving it back into a variable modifiedJsonData and replacing it back into the directory.
$modifiedJsonData = json_encode($data, JSON_PRETTY_PRINT); file_put_contents($fil, $modifiedJsonData);
It seems to work partially, but not completely, rather than just replacing (ID).
As shown below: $data['entity']['payments'][0]['state']['id']
It replaces the entire JSON content, not just the above content, the JSON content should be more than the following content:
{ "entity": { "payments": [ { "state": { "id": ##### } } ] } }
Please help, I may have done something wrong
I can also bypass it by:
When decoding JSON using json_decode(), make sure you have the correct JSON text in $jsonData, and use two flags in the current scenario, the first flag is always used, the second flag is more specific:
JSON_THROW_ON_ERROR
JSON_BIGINT_AS_STRING
Example:
(Since PHP 8.0)
(Since PHP 7.3)
JSON_THROW_ON_ERROR
The reason why we only see the JSON of
$data['entity']['payments'][0]['state']['id']
is because$data = The json_decode(...)
operation returnednull
because the parsing failed. UsingJSON_THROW_ON_ERROR
will convert any errors into exceptions, which are easier to spot because it will stop the execution of the script on the error.This avoids looking for errors in subsequent output.
JSON_BIGINT_AS_STRING
BIGINT refers to BigInt (ECMA 262), which is a numeric value type in JavaScript for very large (negative and positive) integers that json_decode() may lose precision when processing (3v4l.orgDemo):