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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With