3

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?

Shujaat
  • 691
  • 4
  • 18
PrimuS
  • 2,505
  • 6
  • 33
  • 66

3 Answers3

2

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"}]
DevDonkey
  • 4,835
  • 2
  • 27
  • 41
1

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",
        ....
    )
));
michelem
  • 14,430
  • 5
  • 50
  • 66
1

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",
        ....
    )
));
Jerodev
  • 32,252
  • 11
  • 87
  • 108