3

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.

3 Answers 3

11

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.
    Commented Nov 9, 2021 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. Commented Nov 10, 2021 at 7:32
  • Thanks for the explanation, must've overlooked that!
    – Louis B.
    Commented Nov 10, 2021 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
    Commented Jul 19, 2019 at 6:00
  • see my updated answer
    – Waqar Ali
    Commented Jul 19, 2019 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 Commented Jun 29, 2020 at 17:02
0

If you still need to use the old json helper \Magento\Framework\Json\Helper\Data, i.e. you are implementing \Magento\ImportExport\Model\Import\Entity\AbstractEntity that has:

protected $jsonHelper;

built with the old helper by constructor, you still can overwrite the constructor of the abstract class in yours, and use a custom class to override $jsonHelper, like this one:

<?php
namespace Vendor\Module\Model;

use InvalidArgumentException;
use Magento\Framework\Serialize\Serializer\Json;

class JsonSerializer extends Json
{
    /**
     * Serialize data into string
     *
     * @param mixed $data
     * @return string|bool
     * @throws InvalidArgumentException
     */
    public function jsonEncode($data)
    {
        return $this->serialize($data);
    }

    /**
     * Unserialize the given string
     *
     * @param string $string
     * @return mixed
     * @throws InvalidArgumentException
     */
    public function jsonDecode(string $string)
    {
        return $this->unserialize($string);
    }
}

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.