json returned from CI REST API is failing jsonlint tests

喜夏-厌秋 提交于 2019-12-20 05:56:47

问题


I have the following code in a codeigniter REST app (built using: https://github.com/chriskacerguis/codeigniter-restserver)

public function fullname_get()
{
   $fullname = array("fname"=>"john", "lname"=>"doe");
   $data["json"] = json_encode($fullname);
   $this->response($data["json"], 200);
}

When I call the API, this return json that looks like this:

{\"fname\":\"john\",\"lname\":\"doe\"}

The above json string fails http://jsonlint.com/ test because of the escape character "\". Just wondering how I can work around this? I'm building a REST api that is supposed to return json ... and I have to make sure it's legit json.

Thanks.


回答1:


Try this

 $fullname = array("fname"=>"john", "lname"=>"doe");
 $this->response($fullname, 200);//it sends data json format. You don't need to json encode it

You got that response because your data is json encoded twice




回答2:


You have to strip slashes, use this stripslashes(json_encode($fullname)). Full code mention below:

public function fullname_get()
{
   $fullname = array("fname"=>"john", "lname"=>"doe");
   $data["json"] = stripslashes(json_encode($fullname));
   $this->response($data["json"], 200);
}

I hope this will solve your issue.




回答3:


It is legit JSON - and you didn't write a test ;)

{
    "fname": "john",
    "lname": "doe"
}

Please see the demo over at http://ideone.com/5IW1Ef


The class you are using does magical things:

$this->response($this->db->get('books')->result(), 200);

and based on the format specified on the URL the response data is converted to JSON. You don't have to do the JSON encoding.

Please read the examples provides here https://github.com/chriskacerguis/codeigniter-restserver#responses

 $fullname = array("fname"=>"john", "lname"=>"doe");
 $this->response($fullname, 200);

http://code.tutsplus.com/tutorials/working-with-restful-services-in-codeigniter-2--net-8814



来源:https://stackoverflow.com/questions/27972580/json-returned-from-ci-rest-api-is-failing-jsonlint-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!