Saadia Saadia - 7 months ago 21
PHP Question

Getting rid of double quotes in JSON

I need to get rid of double quotes in my JSON string, this is how I am forming an array and then converting it to JSON

$dinnerDetails = array();
foreach ($dinners as $dinner) {
$dinnerDetails[] = array(
"title" => $dinner->getName(),
"data" => $dinner->getDate()
);
}

$dinnerDetails = json_encode($dinnerDetails);


Inside my view when i dump
$dinnerDetails
I see the following

string '[
{
"title": "Formal Dinner",
"data": "Tue Apr 05 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Tue Apr 05 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Black Tie",
"data": "Wed Apr 13 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Fri Apr 08 2016 05:00:00 GMT+0500 (PKT)"
}
]


and when I assign this to a JS variable this is how see it in the source

var dinners = [
{
"title": "Formal Dinner",
"data": "Tue Apr 05 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Tue Apr 05 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Black Tie",
"data": "Wed Apr 13 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Fri Apr 08 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Sat Apr 16 2016 05:00:00 GMT+0500 (PKT)"
},
{
"title": "Formal Dinner",
"data": "Mon Mar 28 2016 05:00:00 GMT+0500 (PKT)"
}
];


I am using Symfony framework and this is how I am passing
$dinnerDetails
to view

return $this->render('AppBundle:admin/college:edit.html.twig', array(
'dinners' => $dinnerDetails
));


and then inside twig I am assigning to js variable like this

var dinner = jQuery.parseJSON(dinners);


In JS i even tried doing
JSON.parse(dinners.replace(""",'"'));
but this does not help.

The output that I am looking for is something like this

[
{
title: "All Day Event",
date: "Fri Apr 08 2016 05:00:00 GMT+0500",
},
{
title: "Long Event",
date: "Fri Apr 08 2016 05:00:00 GMT+0500",
},
]


I will really appreciate a help here.

Answer

try the raw-filter in your template. Something like this:

{{ dinners|raw }}

2nd. you have serialized a PHP-Object into a JSON-string.
If you paste this string inside a script-block this string will be interpreted as JS.
It is JS-code now, not a string anymore. You don't have to parse it; actually you cannot parse it.

<script> var dinner = {{ dinners|raw }}; </script>