Search code examples
phpjsonsymfonyresponsejsonresponse

How to format JSON output in Symfony


I have a script that expects the following output:

[{
    "id": "288",
    "title": "Titanic",
    "year": "1997",
    "rating": "7.7",
    "genre": "drama, romance",
    "od": "0"
}, {
    "id": "131",
    "title": "The Bourne Identity",
    "year": "2002",
    "rating": "7.9",
    "genre": "action, mystery, thriller",
    "od": "1"
}]

That does not look like well formatted json, as when I do this:

return new JsonResponse(array(
        "id" => 288,
        "title" => "Titanic",
        "year" => "1997",
        ....
    ));

I am getting this:

{

"id": ​288,
"title": "Titanic",
"year": "1997"
....
}

The plugin I am using is this, and it even has a $.getJson Function?!?

How would I change the output format?


Solution

  • its just missing its outer container.

    try this:

    return new JsonResponse( array( array(
      "id"    => 288,
      "title" => "Titanic",
      "year"  => "1997"
    )) );
    

    this should output as:

    [{"id":288,"title":"Titanic","year":"1997"}]