unable to get jsonEncode in magento2

12,929

Solution 1

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;
}

Solution 2

Using \Magento\Framework\Json\Helper\Data is deprecated from Magento 2.2 onward, for versions >= 2.2, you can use SerializerInterface

From the Magento 2 devdocs: https://devdocs.magento.com/guides/v2.2/extension-dev-guide/framework/serializer.html#json-default

use Magento\Framework\Serialize\SerializerInterface;

/**
 * @var SerializerInterface
 */
private $serializer;


public function __construct(SerializerInterface $serializer) {
  $this->serializer = $serializer;
}


public function encodeSomething($data) {
    return $this->serializer->serialize($data)
}

public function decodeSomething($data) {
    return $this->serializer->unserialize($data)
}

That ends up calling a class which runs json_encode() and json_decode() https://github.com/magento/magento2/blob/2.2/lib/internal/Magento/Framework/Serialize/Serializer/Json.php

So, if you're running on 2.1 or lower, you could use native PHP functions json_encode() and json_decode() and get the same result, or use the deprecated \Magento\Framework\Json\Helper\Data

Solution 3

Try :

echo $this->helper(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($array);

or

$jsonHelper = $this->helper('Magento\Framework\Json\Helper\Data');
echo $jsonHelper->jsonEncode($array);
Share:
12,929
vijay b
Author by

vijay b

DevOps technologies,Automation , java microservices

Updated on June 09, 2022

Comments

  • vijay b
    vijay b almost 2 years

    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?