Fosrestbundle: JSON pretty print

Created on 20 May 2014  路  6Comments  路  Source: FriendsOfSymfony/FOSRestBundle

I'd like to have the JSON output of my API pretty printed. As far as I can tell, there is no out of the box option for this. Is that correct?

I've been digging through the code and found that JMS\Serializer\JsonSerializationVisitor is the thing doing the actual json encoding. If I pass JSON_PRETTY_PRINT as option to the json_encode call there, I get the output I want. So far I've not found a way to actually have the options of this object modified through FOSRestBundle. I've also been looking at simply registering a new format handler, ie "prettyjson", though there simply are to many layers and magic config for me to easily dig through. I'm new to Symfony so a lot of the indirection is still mysterious to me.

This is primarily a question, though if this cannot easily be done yet, it's also a feature request.

Most helpful comment

Haha. That is so simple. And so obvious if you are used to working with Symfony Bundles. Thanks.

jms_serializer:
    visitors:
        json:
            options: JSON_PRETTY_PRINT

All 6 comments

JMSSerializerBundle already allows to configure the options passed to json_encode: http://jmsyst.com/bundles/JMSSerializerBundle/master/configuration#extension-reference

btw, you don't need to pass the computed bitmask. You can also pass a string being the name of a JSON constant, or an array of constant names to combine them. It will normalize them by building the corresponding bitmask

Haha. That is so simple. And so obvious if you are used to working with Symfony Bundles. Thanks.

jms_serializer:
    visitors:
        json:
            options: JSON_PRETTY_PRINT

Is there any way to do it at run time?

@kuroisuna it is up to your serializer, not to fosrestbundle.

If anyone ever want to create a service that can pretty print json with JMS serializer but without JMS bundle, here is some yaml porn:

umpirsky.serializer.json.pretty_print:
    class: JMS\Serializer\Serializer
    public: true
    factory:
        - !service
            class: JMS\Serializer\SerializerBuilder
            calls:
                - method: setSerializationVisitor
                arguments:
                    - 'json'
                    - !service
                        class: JMS\Serializer\JsonSerializationVisitor
                        calls:
                            - method: setOptions
                            arguments:
                                - '@=constant("JSON_PRETTY_PRINT")'
                        arguments:
                            - !service
                            class: JMS\Serializer\Naming\SerializedNameAnnotationStrategy
                            arguments:
                                - !service
                                    class: JMS\Serializer\Naming\IdenticalPropertyNamingStrategy
        - 'build'
Was this page helpful?
0 / 5 - 0 ratings