问题
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