繁体   English   中英

json字符串未转换为对象

[英]json string is not converting into object

这是我试图发送json的服务器端代码

$x = array();
$timestamp = strtotime('22-09-2008'); 
$x["x"] = $timestamp;
$x["y"] = 22;

$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo json_encode($val);

所以上面代码的输出看起来像

   "[{ \"name\": \"weight\", \"dataPoints\": [{\"x\":1222041600,\"y\":22}] }]"

下面是我通过Jquery getJSON获取数据的客户端代码

var jqxhr = $.getJSON( "https://domain/gettracker.php?id="+id, function(data) {

 console.log(data);

})

我想getJson会自动将json转换为对象,但它会记录下面的原始json

"[ {  name: "weight", dataPoints: [{"x":1222041600,"y":22}] } ]"

我试着做json解析,但是我得到了错误。

我想我不是通过php正确发送数据。有人可以指导我吗?

您的JSON字符串无效 - 属性名称应该用双引号括起来 - " ,您不需要再次对字符串进行编码。

$val = '[{ "name": "weight", "dataPoints": ['.json_encode($x).'] }]';
echo $val;

或者更好的是,使用json_encode为您创建字符串:

$data = array(
    'name' => 'weight',
    'dataPoints' => $x
);

echo json_encode($data);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM