如何在Symfony中格式化JSON输出

3
我有一个脚本,期望得到以下输出:
[{
    "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"
}]

这看起来不像格式良好的JSON,因为当我这样做时:

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

我得到了这个:
{

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

我正在使用的插件是this,它甚至有一个$.getJson函数?!?
我该如何更改输出格式?
3个回答

2

它只是缺少外层容器。

试试这个:

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

这应该输出为:

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

1

你需要将items数组包含在父级数组中:

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

1
你需要将数据放入另一个数组中以创建项目数组。只需在现有数组外面包裹另一个数组即可:
return new JsonResponse(array(
    array(
        "id" => 288,
        "title" => "Titanic",
        "year" => "1997",
        ....
    )
));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接