Drupal.toJson object encoding errors

mathiaz.sk - April 5, 2009 - 21:24
Project:JSON server
Version:6.x-1.x-dev
Component:Code
Category:bug report
Priority:normal
Assigned:Unassigned
Status:needs review
Description

From PHP documentation:

- Common JSON mistakes

<?php
// 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);
  }

 
 

Drupal is a registered trademark of Dries Buytaert.