Rendering a JSON in Symfony [Problem with special characters]

I'm working on a project with symfony and I'm using the php function file_get_contents to return the content of this page https://db.satnogs.org/api/satellites/?format=json which is basically a json format content.

the problem is when I render the content to the twig file the format changes like this

[{"id":4105855,"start":"2021-05-14T10:45:53Z","end":"2021-05-14T10:50:41Z","ground_station
...

I tried to clean the special characters by replacing " to " and I still got a problem because the backslash character also disappeared while rendering

for instance, this is the normal json format that I want to render

"client_metadata":"{\"radio\": {\"name\": \"gr-satnogs\",
...

here's the version that I have after rendering the json file

"client_metadata":"{"radio": {"name": "gr-satnogs",

I tried to put back the \ character but I didn't figure it out

My question is why does the render function in symfony alters the format of the file and do you know how to render the correct format in symfony (do I have to precise some encoding format in the parameter of the render function maybe) ?

I would be really grateful if you could help me! :)

2 answers

  • answered 2021-05-15 17:44 dandemo

    You can fix this by using the javascript decodeURI() function. In PHP, it is urldecode().

    console.log(decodeURI(document.getElementById("mycode").innerHTML));
    <div id="mycode">[{&quot;id&quot;:4105855,&quot;start&quot;:&quot;2021-05-14T10:45:53Z&quot;,&quot;end&quot;:&quot;2021-05-14T10:50:41Z&quot;}]</div>

  • answered 2021-05-15 17:52 akrys

    I assume, your json code is in a variable like json.

    Usually, all output variables are escaped in twig. So, I think you've done something like this:

    {{ json }}

    If you're sure the data is save without being escaped, you can use the raw modifier:

    {{ json|raw }}