35

I am trying to use twig json_encode function but when I do this

    var packageDetails =  {{(packageDetails|json_encode)}};

and packageDetails is an array of array passed from controller

It gives me error saying

    invalid property id 

because of " so I want to use escape filter; how do I use it?

3 Answers 3

67

Is it simply because you are not wrapping your output in quotes?

var variable = '{{{reference}}}';

Update:

The actual answer to solve the question was adding |raw to the tag as per comments

var packageDetails =  {{(packageDetails|json_encode|raw)}};
Sign up to request clarification or add additional context in comments.

5 Comments

If i wrap my output in quotes i don't get json objcect. when i console.log it I get {"college":....
I want my js variable to store an object which i can loop through
If your string contains a ' sign, the JS will break. Use the "escape('js')" twig filter to avoid that. So, I suggest : var variable = '{{reference | json_encode | escape('js') | raw}}';
Had the same &quot problem, so the | raw comment saved my ass. Thanks!
@paulgreg Do you really need | raw here?
45

You can add the options in the following way:

{{ data|json_encode(constant('JSON_PRETTY_PRINT'))|raw }}

Adding this because it answers the question in your title, but it sounds like the raw filter was really what you were looking for. Still, others may find this useful.

3 Comments

Isn't dangerous for XSS attack using the raw filter ?
@Frank6: Depends where data came from; if it's from your own database query or similar, it's pretty safe. If it's from user input then it should be sanitized before being passed to the Twig view
Good ! now it's not giving me Unexpected token in JSON at position error.change JSON.parse('{{ cats|json_encode|raw }}'); with {{ cats|json_encode(constant('JSON_PRETTY_PRINT'))|raw }}
4

For anyone, who has similar problem with Blade / Laravel5.x

var v = JSON.parse('{!! $v !!}');

3 Comments

No use of double { ? The variable is $v or is just a parameter. Even if not using Laravel or blade the answer isnt clear
You seriously think I know anything about an answer I gave like 4 years ago? ;)
Probably not, but that can be answered by anyone who reads this and has Blade / Laravel5.x fresh and in mind.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.