删除JSON结果中的双引号? [英] Remove double quotes in JSON result?
问题描述
我的代码如下
foreach($location_total_n_4 as $u=> $v) {
$final_location_total_4 .= "[".$u.",".$v."],";
}
我将这些值作为JSON发送.
I'm sending these values as JSON.
echo json_encode(array("location"=>"$final_location_total_4" ));
这是我的response
对象的外观:
{
"location": "[1407110400000,6641],[1407196800000,1566],[1407283200000,3614],"
}
我正在用ajax创建成功图,所以我需要这样,
I'm creating graph on success with ajax.so I need it like this,
{
"location": [1407110400000,6641],[1407196800000,1566],[1407283200000,3614],
}
有人可以帮我解决这个问题吗?
Can anyone help me to solve this?
推荐答案
问题是您的location
值是非正确的序列化值.在服务器端进行修复绝对合适(看起来像是在尝试实现自己的json_encode并失败了),但也可以在客户端进行修复.一种可能的方法:
The problem is that your location
value is non-properly serialized value. It's definitely appropriate to fix on the server-side (looks like one's trying to implement their own json_encode and failing), but it's possible to fix on the client-side as well. One possible approach:
var location = JSON.parse('[' + response.location.slice(0,-1) + ']');
演示 . slice(0,-1)
删除结尾的逗号,然后将内容包装在方括号中,将其转换为适当的JSON(至少对于给定的数据集而言).
Demo. slice(0,-1)
removes the trailing comma, then the contents are wrapped into brackets, turning them into a proper JSON (at least for the given dataset).
对于服务器端,事实证明我是对的:这段代码...
As for server-side, turned out I was right: this code...
foreach($location_total_n_4 as $u=> $v) {
$final_location_total_4 .= "[".$u.",".$v."],";
}
echo json_encode(array('location' => "$final_location_total_4"));
...在策略上(总是添加结尾逗号)和策略上(都不应解决语言本身已经解决的任务)都是错误的.一种可能的替代方法:
... is wrong both tactically (always adding a trailing comma) and strategically (one shouldn't solve the task already solved by the language itself). One possible replacement:
$locations = array();
foreach ($location_total_n_4 as $u => $v) {
$locations[] = array($u, $v);
}
echo json_encode(array('location' => $locations));
最重要的是:除非您真的知道自己在做什么,否则不要尝试实现自己的序列化协议.
The bottom line: never attempt to implement your own serialization protocol unless you're really know what're you doing.
这篇关于删除JSON结果中的双引号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!