public function __construct(
   JsonFactory $resultJsonFactory
   $this->resultJsonFactory = $resultJsonFactory;
$response = $this->resultJsonFactory->create();
$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

2 Answers 2

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

  • 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 Feb 26, 2018 at 14:16
  • Thanks, my mistake. Just edited my answer. Feb 26, 2018 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 Feb 26, 2018 at 15:05

Some years late but you can use following workaround for what you needed : )

    /** @var  \Magento\Framework\App\ResponseInterfaceFactory $responseFactory */
    $response = $responseFactory->create();
    $resultData = json_decode($response->getBody(), true);
    //manipulate data as needed and set it again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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