0

Sorry for the stupid question, but I don't know a thing about JavaScript. I'm trying to use JSON.stringify to make an array looking pretty and be easy to read.

I tried this in controller:

    $metadata = '{"hello":"world", "Test":["hello"]}';
    $data = json_encode($metadata);

    return $this->render('AcmeQuotesBundle:Home:metadata.html.twig', array('data' => $data));

and this in template:

   <script>
        var obj = {{ data }}

        document.body.innerHTML = "";
        document.body.appendChild(document.createTextNode(JSON.stringify(obj, null, 4)));
    </script>

but I get a white screen.

How I can make it work?

6
  • SyntaxError: syntax error localhost/my-quotes/web/app_dev.php/metadata/1 Line 19 Commented Sep 25, 2012 at 12:36
  • Semicolon missing? var obj = {{ data }}; Commented Sep 25, 2012 at 12:36
  • No :( it is pointing to &quot; in this: var obj = &quot;{\&quot;hello\&quot;:\&quot;world\&quot;, \&quot;Test\&quot;:[\&quot;hello\&quot;]}&quot;; Commented Sep 25, 2012 at 12:38
  • Try this: var obj = {{ data|raw }}; Commented Sep 25, 2012 at 12:39
  • Now I get the text, but it's on one line, I would like to print it like this jsfiddle.net/AndyE/HZPVL Commented Sep 25, 2012 at 12:41

1 Answer 1

3

Try the below

var obj = {{ data|raw }};
Sign up to request clarification or add additional context in comments.

1 Comment

console.log(JSON.stringify({{ data|raw }}, null, 4));

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.