【问题标题】:Malformed JSON in slim framework苗条框架中的格式错误的 JSON
【发布时间】:2018-06-26 20:18:06
【问题描述】:

我在路线中有这个:

echo '{"result":{"code":"200","status":"success","data":'.$response->withJson($rows,200,0).'}}';

返回此 JSON:

{"result":{"code":"200","status":"success","data":HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8 [{"id":23,"ragionesociale":"consumatore","indirizzo":"000","comune":"000","provincia":71,"cap":"000","idprovincia_camera":71,"telefono":"000","fax":"000","sitoweb":"0","email":"info@000.it","codice_promo":"xxxxx","password":"xxxxx","data_adesione":"2014-09-26 07:52:23","attivato":1,"costo":0,"tipologia":1,"iva":22,"alias":"prova-it4italy-srl","pagamento":1,"merchantorderid":null,"mybankid":null,"pending":0,"paymentid":null,"logo":"","nome":null,"cognome":null,"sesso":1,"datanascita":null,"eta":null,"nazione":null,"tipologia_utente":1,"fb_token":null,"fb_id":null,"gp_token":null,"gp_id":null,"profile_img":null,"citta":null,"param":null}]}}

问题是我在数据中收到了第二个响应标头,它破坏了 JSON。 我想得到这样的回应:

{"result":{"code":"200","status":"success","data":[{"id":23,"ragionesociale":"consumatore","indirizzo":"000",....

有没有办法在 JSON 中不打印 HTTP/1.1 200 OK Content-Type: application/json;charset=utf-8 部分?

【问题讨论】:

  • 您使用 withJson 方法从 slim 获取标题的帮助,如果您不想要,只需使用 json_encode 函数。但我建议你坚持使用 $response->withJson 方法并在将它们编码为 json 之前管理你的数据($rows 和其他东西)。
  • 看起来你过于复杂了。通常,如果您有一些数据要以 JSON 格式返回,您只需执行 return $response->withJson($data); 这会自动设置状态代码 200 并表示成功。

标签: arrays json slim


【解决方案1】:

$response->withJson() 中,响应的 Content-Type 自动设置为 application/json;charset=utf-8,以及默认的 200 HTTP 状态代码。所以你不必手动添加。

response->withJson()

所以只需执行以下操作就足够了。

$result = new stdClass(); 
$result->result = new stdClass(); 
$result->result->code = "200";
$result->result->status= "success";
$result->result->data = $rows;

echo $response->withJson($result);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-22
    • 2016-03-28
    • 2017-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多