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

rypit’s picture

Version: 6.x-1.x-dev » 6.x-2.x-dev

This bug still exists in 6x.2x-dev. The fix to the JS for Drupal.service is outlined above.

skyredwang’s picture

Status: Needs review » Closed (fixed)
mhrabovcin’s picture

Status: Closed (fixed) » Needs review
StatusFileSize
new439 bytes

The JS part is still not fixed, attaching patch.

skyredwang’s picture

Status: Needs review » Closed (fixed)

php compatibility issue has been fixed in the new alpha

mhrabovcin’s picture

Status: Closed (fixed) » Needs work

This isn't a problem of PHP but JSON that is produced on client side. Simple example:

// This is what is produced by Drupal.toJson function in current version. PHP can't handle extra commas
// and json_decode will return NULL variable
$str = '{"test":{"a":"b",},}';
print_r(json_decode($str));

// After applying patch this output is produced and PHP can parse JSON string properly
$str = '{"test":{"a":"b"}}';
print_r(json_decode($str));

This patch is removing extra commas from produced JSON string.

skyredwang’s picture

We should prevent creating the bad json at first place instead of massaging the output. I am not sure how the extra "," got created.

mhrabovcin’s picture

Its 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.

skyredwang’s picture

The 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.

mhrabovcin’s picture

StatusFileSize
new766 bytes

You are right, here is proper fix.