Search code examples
twigtwig-filter

Why isn't there a native json_decode in Twig?


I know how to set up a json_decode function in twig.. but why is there no native support for decoding in twig? I can easily call json_encode without setting up a Twig Filter, but that is not the case for json_decode.

It seems logical to have it has a native function. Am I missing the rational behind not having it? Maybe it's computationally expensive?


Solution

  • json_encode makes sense, json_decode however does not really.

    It adds a non trivial dependency towards the fact that the data passed is JSON.

    Filters are here to transform data not crafting data. Computations (that are not transformations) should be made ahead of time.

    One could also argue that json_encode should be done ahead of time but considering how frequent it is to return/send JSON it seems fair enough to do it in the template.

    PS :
    This seems to be a primarily opinion based question (unless there is an official answer to it).