简体   繁体   中英

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?

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

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",
        ....
    )
));

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",
        ....
    )
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM