【问题标题】:PHP 5.4 json_decode generates malformed jsonPHP 5.4 json_decode 生成格式错误的 json
【发布时间】:2017-12-29 13:19:28
【问题描述】:

我确实有一个关于 PHP 数组到 JSON 序列化的奇怪问题:

我得到了一个包含许多层和一定大小的数组,它工作得很好。但在某些时候,返回的 JSON 对象中缺少右大括号。 这是返回的标头。

Date: Fri, 29 Dec 2017 12:42:39 GMT
Server: Apache/2.2.22 (Debian)
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, userid, dealerid
Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT
X-Powered-By: PHP/5.4.45
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 8503
X-UA-Compatible: IE=edge
Content-Type: application/json;charset=utf-8

API 是使用 SLIM 3 框架构建的,用于简单的 REST API。

API 上的设置:

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
...

public function listFailedOrders(Request $request, Response $response, array $args) {
  $arr = [];

  //algorithm to fill array
  //verified that the array has data that is not malformed in any way!

  $responseData = [];
  $responseData['count'] = count($arr);
  $responseData['data'] = $arr;

  $response = $response->withJson($responseData, 200);
  return $response;

}

返回数据:

{
	"count": "41",
	"data": [
		{
           .... JSON DATA ....
		},
		{
           .... More JSON Data ....
		}
	]
//Missing End curly Bracket

我使用 Insomnia Rest 客户端来检查这一点,直到此时,我对这个问题的唯一解决方案是在接收端添加一个右大括号。

TLDR: 我将一个大的(不限制到达对象)序列化为 JSON,但尾随的花括号被修剪。问题出在哪里?

【问题讨论】:

  • 1.尝试增加memory_limit, 2. 如果没有帮助,那么设置:error_reporting(E_ALL); ini_set('display_errors', 1); 如果存在错误将显示错误。 3.尝试用echo json_encode($rawArrayOrObject); exit(0); 回显数据
  • 我可以解决内存限制问题。内存限制设置为 2GB,发送的数据仅为 10KB
  • 5 mb 是可以的,但如果为非序列化对象分配内存,它可能会更多。想想 ORM 等类型的对象,你有 2 个字段和 10 种使用这 2 个字段进行操作的方法
  • 当回显 json_encode 时,大括号实际上就在那里。我猜这是苗条的问题!
  • 不要再次分配给变量 $response,只需返回上一行并查看差异。试一试。 :)

标签: php json


【解决方案1】:

问题是预设的内容长度标头切断了最后一个大括号。 这是一个严重的错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 2012-11-28
    • 2020-03-29
    • 2020-03-18
    • 2013-12-10
    • 2011-01-21
    相关资源
    最近更新 更多