如何在Symfony中格式化JSON输出

时间:2022-07-26 22:48:20

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:

这看起来不像格式良好的json,就像我这样做:

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?!?

我正在使用的插件就是这个,它甚至还有一个$ .getJson函数?!?

How would I change the output format?

我该如何更改输出格式?

3 个解决方案

#1


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

#2


1  

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

您必须将items数组包含在父数组中:

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

#3


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

#1


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

#2


1  

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

您必须将items数组包含在父数组中:

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

#3


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