删除JSON结果中的双引号? [英] Remove double quotes in JSON result?

查看:383
本文介绍了删除JSON结果中的双引号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆