From PHP documentation:
- Common JSON mistakes
// the following strings are valid JavaScript but not valid JSON
// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null
// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null
// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null
Drupal.toJson is making second and third. Solution:
case 'object':
var output = "{";
for(i in v) {
output = output + '"' + i + '"' + ":" + this._toJson(v[i]) + ",";
}
if (output[output.length - 1] == ',') {
output = output.substring(0, output.length - 1);
}
output = output + "}";
return output;
Also json_decode function is returning as default stdClass instead of array. Services module doesn't support object just arrays. Solution:
function drupal_parse_json($v) {
// PHP 5 only
if (function_exists('json_decode')) {
return json_decode($v, TRUE);
}
Comments
Comment #1
rypit commentedThis bug still exists in 6x.2x-dev. The fix to the JS for Drupal.service is outlined above.
Comment #2
skyredwangComment #3
mhrabovcin commentedThe JS part is still not fixed, attaching patch.
Comment #4
skyredwangphp compatibility issue has been fixed in the new alpha
Comment #5
mhrabovcin commentedThis isn't a problem of PHP but JSON that is produced on client side. Simple example:
This patch is removing extra commas from produced JSON string.
Comment #6
skyredwangWe should prevent creating the bad json at first place instead of massaging the output. I am not sure how the extra "," got created.
Comment #7
mhrabovcin commentedIts because module uses custom function in Drupal namespace - Drupal.toJson which creates JSON string. The output means serialized JSON, whcih I am trying to fix by this patch. By applying this patch none extra "," will be created.
Comment #8
skyredwangThe patch only removes trailing "," after the whole JSON string gets created with the trailing ",". That's not a good approach at all. We should fix the creation process if there is indeed a bug.
Comment #9
mhrabovcin commentedYou are right, here is proper fix.