如何在 Symfony 中格式化 JSON 输出
How to format JSON output in Symfony
我有一个需要以下输出的脚本:
[{
"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
功能?!?
如何更改输出格式?
您必须将项目数组包含到父数组中:
return new JsonResponse(array(
array(
"id" => 288,
"title" => "Titanic",
"year" => "1997",
....
),
array(
"id" => 288,
"title" => "Titanic",
"year" => "1997",
....
)
));
它只是缺少外容器。
试试这个:
return new JsonResponse( array( array(
"id" => 288,
"title" => "Titanic",
"year" => "1997"
)) );
这应该输出为:
[{"id":288,"title":"Titanic","year":"1997"}]
您必须将数据放在另一个数组中才能创建项目数组。只需将现有数组包装在另一个数组中:
return new JsonResponse(array(
array(
"id" => 288,
"title" => "Titanic",
"year" => "1997",
....
)
));
我有一个需要以下输出的脚本:
[{
"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
功能?!?
如何更改输出格式?
您必须将项目数组包含到父数组中:
return new JsonResponse(array(
array(
"id" => 288,
"title" => "Titanic",
"year" => "1997",
....
),
array(
"id" => 288,
"title" => "Titanic",
"year" => "1997",
....
)
));
它只是缺少外容器。
试试这个:
return new JsonResponse( array( array(
"id" => 288,
"title" => "Titanic",
"year" => "1997"
)) );
这应该输出为:
[{"id":288,"title":"Titanic","year":"1997"}]
您必须将数据放在另一个数组中才能创建项目数组。只需将现有数组包装在另一个数组中:
return new JsonResponse(array(
array(
"id" => 288,
"title" => "Titanic",
"year" => "1997",
....
)
));