1

I have a private template in which a JSON string can be passed in but when the string is not JSON compatible I want to provide something helpful, not just have the template fail.

For example, I'm dynamically building an entries query which could have field scopes or other entry query parameters appended, so I want an optional filters URL parameter to be allowed to pass a JSON string.

  • Thus a parameter of filters={"level":3} passes valid JSON but filters={level:3} does not.
  • Let's say the parameter is captured in a variable called filters
  • So in the first case filters|json_decode works but in the second it generates an error.

I'd like to be able to do something like:

{% set valid = filters|json_decode is iterable %}

…and then provide error messaging on false.

But I can't. I just get a yii syntax error template failure when the string isn't valid.

Is there a solution?

1 Answer 1

2

I don’t think you can catch exceptions in Twig (at least without an extension).

Craft has a handy Json helper class that contains a decodeIfJson() method that returns a decoded string, if the provided value is valid JSON, otherwise the value itself.

You can create an instance of this class using the create function, call decodeIfJson(filters) on it, and check the result against the value of filters. If the result is the same as the value, it must be invalid JSON (unless the value is an integer, in which case they would be the same).

{% set jsonHelper = create('\\craft\\helpers\\Json') %}
{% set decoded = jsonHelper.decodeIfJson(filters) %}
{{ decoded == filters ? 'Invalid' : 'Valid' }} JSON
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.