1
public function __construct(
   JsonFactory $resultJsonFactory
)
{
   $this->resultJsonFactory = $resultJsonFactory;
}
$response = $this->resultJsonFactory->create();
$response->setHttpResponseCode(406);
$response->setData(['error_code' => '111','subscription' => '222']);
...
// now i want to add new_item to the array in response 
// without clearing the previous set content. 
$response->setData('new_item' => '333')

I can see that setData it is using Zend_Json::encode

public function setData($data, $cycleCheck = false, $options = [])
{
    $this->json = \Zend_Json::encode($data, $cycleCheck, $options);
    return $this;
}

but I can't find if it is an option to insert instead of set

0
public function setData($data, $cycleCheck = false, $options = [])
{
    $this->json = \Zend_Json::encode($data, $cycleCheck, $options);
    return $this;
}

As we can see, when trying to set json data, the previous data are always overridden by the new data.

In your case, we can try to use a variable data array. For example:

$response = [
            'errors' => false
        ];

//Condition 1

$response = ['errors' = true, 'error_code' => '111','subscription' => '222']

//Condition 2

$response['new_item'] = 3333;
...
//Final Condition
...

//Set final data

$response->setData($response);
  • Hi thanks for answer but the code in condition 2 will give and error and your solution don't add an element to the current array. i can see debugging that the data is in a json method inside the class but my problem is to get the body in magento (no js) and add the new element and setData again with the new value – open-ecommerce.org Feb 26 '18 at 14:16
  • Thanks, my mistake. Just edited my answer. – Khoa TruongDinh Feb 26 '18 at 14:39
  • thanks but still if I undertood your approach is to convert the json into an array and add a new element and setData again but i don't see any method inthe json factory object to render the body. thats why i can't accept the solution – open-ecommerce.org Feb 26 '18 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.