The accepted solution doesn't work (anymore ?) because of twig autoescaping the outputs, changing all the JSON " with ".
Equivalent would now have to use the raw filter:
<script type="text/javascript">
nickname = {{ profile.nickname|json_encode()|raw }}; // Nickname will be a string
// 2nd solution if you have more informations related to profile
profile = {
nickname: {{ profile.nickname|json_encode()|raw }},
lastname: {{ profile.lastname|json_encode()|raw }}
};
// Profile is now an object with a nickname property.
// use profile.nickname on your javascripts
</script>
That being said, directly printing the raw JSON into the javascript may cause some problems, has in this configuration:
<script>
var myvar = {{ '{"test": "</script>"}'|raw }};
</script>
The </script> tag in the JSON would be interpreted by the HTML parser, resulting in a broken script.
The truly correct way to do this would rather be to print the JSON as an escaped string, and then parse it within the js script:
<script>
var myvar = JSON.parse('{{ '{"test": "</script>"}'|e('js') }}');
</script>