Njord12 Njord12 - 1 year ago 183
JSON Question

json_decode returns syntax error with a valid json

I'm trying to decode the following json which I have checked with jsonlint and returns that it is a valid json:

[{"gatewayId": "5154979870408704", "sensorId": "5698497110081536"}, {"timestamp": "20160513T225959000Z", "tagId": "123456789AB1", "io": "in"}, {"timestamp": "20160513T235959000Z", "tagId": "123456789AB2", "io": "out"}]

However the result is always Syntax Error when I call json_last_error_msg()
Here is my code:

$param = substr($HTTP_RAW_POST_DATA, 1);
$param =utf8_encode($param);
$json = json_decode($param,true);
echo json_last_error_msg();

The json is being sent to me using curl which is why it is in $HTTP_RAW_POST_DATA, and I'm removing the first character because when making a var_dump I noticed a blank character there, however that's not the problem. Any help is appreciated.
This is the result of var_dump($HTTP_RAW_POST_DATA)

string(187) " [{gatewayId: 5154979870408704, sensorId: 5698497110081536}, {timestamp: 20160513T225959000Z, tagId: 123456789AB1, io: in}, {timestamp: 20160513T235959000Z, tagId: 123456789AB2, io: out}]"

So turns out it was because the double quotes were being removed in the curl request that had the payload like

-d "[{"gatewayId": "5154979870408704", "sensorId": "5698497110081536"}, {"timestamp": "20160513T225959000Z", "tagId": "123456789AB1", "io": "in"}, {"timestamp": "20160513T235959000Z", "tagId": "123456789AB2", "io": "out"}]"

I replaced the double quotes with single quotes in the begining and end of the payload and now its working fine, just leaving this here in case anyone has the same problem.
new payload:

-d '[{"gatewayId": "5154979870408704", "sensorId": "5698497110081536"}, {"timestamp": "20160513T225959000Z", "tagId": "123456789AB1", "io": "in"}, {"timestamp": "20160513T235959000Z", "tagId": "123456789AB2", "io": "out"}]'


Answer Source

In the var_dump I read

string(187) " [{gatewayId: 5154979870408704, ...

Here the key gatewayId is not quoted. The JSON standard requires keys to be strings which use "". The data thus is not valid JSON and PHP rejects it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download