2

As far as I understand, Magento has a JSON encode function by using zend framework. And my question, is there an option to force that function always return JSON object, not JSON array?

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

In native PHP (version 5.3.0 or above), I can achieve it by passing this constant "JSON_FORCE_OBJECT" into the second parameter of json_encode() function. Any help would be greatly appreciated.

  • 1
    Maybe casting the array to an object could work? Mage::helper('core')->jsonEncode((object) $array); – Si Griffiths Apr 3 '14 at 18:40
2

jsonEncode ends up using Zend_Json_Encoder here you will find a function _encodeValue which will either return an array or a object depending on the type of value.

protected function _encodeValue(&$value)
{
    if (is_object($value)) {
        return $this->_encodeObject($value);
    } else if (is_array($value)) {
        return $this->_encodeArray($value);
    }

    return $this->_encodeDatum($value);
}

So if there is a object passed in then there will be an object returned. This really helps with multiple levels. For example.

Mage::helper('core')->jsonEncode(array('test', 'blah')); => ["test","blah"]
Mage::helper('core')->jsonEncode((object) array('test', 'blah')); => {"0":"test","1":"blah"}
Mage::helper('core')->jsonEncode(array('test', (object) 'blah')); => ["test",{"scalar":"blah"}]

Note that there are some special cases when encoding objects. As explained on the zend docs

Encoding PHP objects If you are encoding PHP objects by default the encoding mechanism can only access public properties of these objects. When a method toJson() is implemented on an object to encode, Zend\Json\Json calls this method and expects the object to return a JSON representation of its internal state.

Zend\Json\Json can encode PHP objects recursively but does not do so by default. This can be enabled by passing true as a second argument to Zend\Json\Json::encode().

// Encode PHP object recursively $jsonObject = Zend\Json\Json::encode($data, true); When doing recursive encoding of objects, as JSON does not support cycles, an Zend\Json\Exception\RecursionException will be thrown. If you wish, you can silence these exceptions by passing the silenceCyclicalExceptions option:

  • A very helpful information, thanks for sharing. – Leongelis Apr 4 '14 at 2:53
2

Another method I found and worked like a charm.

$this->getResponse()->clearHeaders()->setHeader('content-type', 'application/json', true);
$this->getResponse()->setBody(json_encode($array));

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.