简体   繁体   English

json字符串未转换为对象

[英]json string is not converting into object

Here is the server side code I am trying to send json 这是我试图发送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);

So output for above code looks like 所以上面代码的输出看起来像

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

Below is the client side code I get the data via Jquery getJSON 下面是我通过Jquery getJSON获取数据的客户端代码

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

 console.log(data);

})

I suppose getJson converts json to object automatically , but it logs the raw json like below 我想getJson会自动将json转换为对象,但它会记录下面的原始json

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

I tried to do json parse , but i get error. 我试着做json解析,但是我得到了错误。

I guess I am not sending the data properly via php.Can some one guide me ? 我想我不是通过php正确发送数据。有人可以指导我吗?

Your JSON string is not valid - the property names should be enclosed in double quotes - " , and you don't need to encode the string again. 您的JSON字符串无效 - 属性名称应该用双引号括起来 - " ,您不需要再次对字符串进行编码。

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

Or better yet, use json_encode to create the string for you: 或者更好的是,使用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