2

I just wanted to know that what is the right way to print array data into json format. I Know we can use php function json_encode() but is this the right way to print array data? Because i saw one of magento's core file, there was something like this

        if (!$_isValidFormKey || !$_isValidSecretKey) {
        $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
        $this->_actionFlag->set('', self::FLAG_NO_POST_DISPATCH, true);
        if ($this->getRequest()->getQuery('isAjax', false) || $this->getRequest()->getQuery('ajax', false)) {
            $this->getResponse()->representJson(
                $this->_objectManager->get(
                    \Magento\Framework\Json\Helper\Data::class
                )->jsonEncode(
                    ['error' => true, 'message' => $_keyErrorMsg]
                )
            );
        } else {
            $this->_redirect($this->_backendUrl->getStartupPageUrl());
        }
        return false;
    }
    return true;
}

so if we look at this section

$this->getResponse()->representJson(
                $this->_objectManager->get(
                    \Magento\Framework\Json\Helper\Data::class
                )->jsonEncode(
                    ['error' => true, 'message' => $_keyErrorMsg]
                )
            );

we see magento is encoding data using \Magento\Framework\Json\Helper\Data class.

I am working on custom APIs where i need to send data in json format. So please correct me if i am not wrong that we can also print Array data using this \Magento\Framework\Json\Helper\Data class.

Thankyou.

7

Nowadays, the recommended dependency to inject would be the \Magento\Framework\Serialize\SerializerInterface.

3
  • Care to elaborate? The serializer provided here seems to use PHP's serialize function, which does not return JSON data. The OP was asking specifically how to serialize data into the JSON format.
    – Louis B.
    Nov 9 at 6:16
  • Actually, Magento\Framework\Serialize\SerializerInterface has had a DI preference for Magento\Framework\Serialize\Serializer\Json for many years now. Even better, the suggested class Magento\Framework\Json\Helper\Data is deprecated since Magento 2.1 (?) and its suggested replacement is Magento\Framework\Serialize\Serializer\Json (which is preferenced through with the mentioned interface). See the Magento core code for reference. Nov 10 at 7:32
  • Thanks for the explanation, must've overlooked that!
    – Louis B.
    Nov 10 at 9:00
1

You cannot use \Magento\Framework\Json\Helper\Data using object manager you can use like this

/**
 * @var \Magento\Framework\Json\Helper\Data
 */
protected $jsonHelper;

/**
 * Constructor.
 * 
 * @param \Magento\Framework\Json\Helper\Data $jsonHelper
 */
public function __construct(\Magento\Framework\Json\Helper\Data $jsonHelper)
{
    $this->jsonHelper = $jsonHelper;
}

/**
 * @param array $dataToEncode
 * @return string
 */
public function encodeSomething(array $dataToEncode)
{
    if (!$_isValidFormKey || !$_isValidSecretKey) {
    $this->_actionFlag->set('', self::FLAG_NO_DISPATCH, true);
    $this->_actionFlag->set('', self::FLAG_NO_POST_DISPATCH, true);
    if ($this->getRequest()->getQuery('isAjax', false) || $this->getRequest()->getQuery('ajax', false)) {
        $this->getResponse()->representJson(
            $this->jsonHelper->jsonEncode(
                ['error' => true, 'message' => $_keyErrorMsg]
        );
    } else {
        $this->_redirect($this->_backendUrl->getStartupPageUrl());
    }
    return false;
}
return true;

} }

You can see This Another Example

3
  • the question is not about using object manager.
    – sudo55
    Jul 19 '19 at 6:00
  • see my updated answer Jul 19 '19 at 6:19
  • @sudo55 Your question was not about using the Object Manager, but how to properly handle JSON data. If you worry about properly doing things in Magento 2, then using the Object Manager properly is actually more important than handling JSON data properly :) Just my 50 cents Jun 29 '20 at 17:02

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.