Search code examples
jsonmagentomagento2

unable to get jsonEncode in magento2


Magento has its own json encode and decode functions:

Mage::helper('core')->jsonEncode($array);  

Above code in depreciated in Magento 2. So how to use jsonEncode, what I have to extend to use json Encode?


Solution

  • Magento 2 way is pass Magento\Framework\Json\Helper\Data using DI functionality (see blow). Don't use $this->helper() and objectManager. This functionality will be deprecated soon.

    /**
     * @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)
    {
        $encodedData = $this->jsonHelper->jsonEncode($dataToEncode);
    
        return $encodedData;
    }