You can use the Serializer Symfony. http://symfony.com/doc/current/components/serializer.html
You might want to write your own Twig extension to do this from your template.
Your code will look something like this:
use Symfony\Component\Serializer\Serializer; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; $encoders = array(new JsonEncoder()); $normalizers = array(new GetSetMethodNormalizer()); $serializer = new Serializer($normalizers, $encoders); $jsonContent = $serializer->serialize($object, 'json');
When you put this line in your javascript, you should have a regular JS object where you can find whatever you want.
You might want to use the JMSSerializerBundle, as it already has a Twig extension, and is easier to use in general.
https://github.com/schmittjoh/JMSSerializerBundle/blob/master/Resources/doc/index.rst
Update to give an overview of what is in the comments.
Both Symfony Serializer, like the JMSSerializerBundle, seem to have difficulty dealing with bidirectional relationships (most likely with the doctrine). This will lead to errors such as "Out of memory" or something regarding Self-referencing objects / infinite loops.
To solve this problem, you can ignore the attribute using Normalizer. Which would look something like this:
use Symfony\Component\Serializer\Serializer; use Symfony\Component\Serializer\Encoder\JsonEncoder; use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer; $normalizer = new GetSetMethodNormalizer(); $normalizer->setIgnoredAttributes(array('match'));
source share