PrimuS
PrimuS

Reputation: 2683

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?

Upvotes: 3

Views: 2276

Answers (3)

Jerodev
Jerodev

Reputation: 33196

You have to put your data in another array to create an array of items. Just wrap the existing array in another array:

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

Upvotes: 1

DevDonkey
DevDonkey

Reputation: 4880

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"}]

Upvotes: 2

michelem
michelem

Reputation: 14590

You have to include the items array into a parent one:

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

Upvotes: 1

Related Questions