json 从 CI REST API 返回 jsonlint 测试失败
json returned from CI REST API is failing jsonlint tests
我在 codeigniter REST 应用程序中有以下代码(构建使用: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);
}
当我调用 API 时,这个 return json 看起来像这样:
{\"fname\":\"john\",\"lname\":\"doe\"}
上面的 json 字符串因转义字符“\”而未通过 http://jsonlint.com/ 测试。
只是想知道我该如何解决这个问题?
我正在构建一个应该 return json 的 REST api ... 我必须确保它是合法的 json。
谢谢。
它是合法的 JSON - 而且你没有写测试 ;)
{
"fname": "john",
"lname": "doe"
}
查看演示
您正在使用的 class 有神奇的作用:
$this->response($this->db->get('books')->result(), 200);
并根据 URL 上指定的格式将响应数据转换为 JSON。您不必进行 JSON 编码。
请阅读此处提供的示例
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
试试这个
$fullname = array("fname"=>"john", "lname"=>"doe");
$this->response($fullname, 200);//it sends data json format. You don't need to json encode it
您收到该回复是因为您的数据 json 编码了两次
你必须去掉斜杠,使用这个 stripslashes(json_encode($fullname))。完整代码如下:
public function fullname_get()
{
$fullname = array("fname"=>"john", "lname"=>"doe");
$data["json"] = stripslashes(json_encode($fullname));
$this->response($data["json"], 200);
}
希望这能解决您的问题。
我在 codeigniter REST 应用程序中有以下代码(构建使用: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);
}
当我调用 API 时,这个 return json 看起来像这样:
{\"fname\":\"john\",\"lname\":\"doe\"}
上面的 json 字符串因转义字符“\”而未通过 http://jsonlint.com/ 测试。 只是想知道我该如何解决这个问题? 我正在构建一个应该 return json 的 REST api ... 我必须确保它是合法的 json。
谢谢。
它是合法的 JSON - 而且你没有写测试 ;)
{
"fname": "john",
"lname": "doe"
}
查看演示
您正在使用的 class 有神奇的作用:
$this->response($this->db->get('books')->result(), 200);
并根据 URL 上指定的格式将响应数据转换为 JSON。您不必进行 JSON 编码。
请阅读此处提供的示例 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
试试这个
$fullname = array("fname"=>"john", "lname"=>"doe");
$this->response($fullname, 200);//it sends data json format. You don't need to json encode it
您收到该回复是因为您的数据 json 编码了两次
你必须去掉斜杠,使用这个 stripslashes(json_encode($fullname))。完整代码如下:
public function fullname_get()
{
$fullname = array("fname"=>"john", "lname"=>"doe");
$data["json"] = stripslashes(json_encode($fullname));
$this->response($data["json"], 200);
}
希望这能解决您的问题。