skip to Main Content

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


  1. Chosen as BEST ANSWER

    I was also able to find away around it by:

     $data = json_decode($jsonData, true, 512, JSON_BIGINT_AS_STRING);
    
    
    
        $data['entity']['payments'][0]['state']['id'] = $logMessageId;
    
            
            
    
    
    
    $modifiedJsonData = json_encode($data, JSON_PRETTY_PRINT);
            
      
      
    
      $existingData = json_decode(file_get_contents($fil), true);
            
         
      
    
      $existingData['entity']['payments'][0]['state']['id'] = $data['entity']['payments'][0]['state']['id'];
    
    
     $updatedJsonData = json_encode($existingData, JSON_PRETTY_PRINT);
            
       
      
    
      file_put_contents($fil, $updatedJsonData);
    

  2. Use JSON_THROW_ON_ERROR with json_decode():

    $data = json_decode($jsonData, true, flags: JSON_THROW_ON_ERROR);
    

    or below PHP 8:

    $data = json_decode($jsonData, true, 512, JSON_THROW_ON_ERROR);
    

    (since PHP 7.3)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search