Monday, February 21, 2011

How do you make php's json_decode compatible with firefox's javascript?

it appears if you have something like

var my_var = {"foo" : "bar"};

in javascript (with firefox at least) and post it to a php server you will receive a string like

{foo:"bar",}

on the server side. But json_decode in php doesn't like the trailing ',' or the lack or quotes around 'foo'. Is there a nice way to clean up the received json string?

The json object is sent with the drupal module json services.

EDIT: This question can be closed. The badly formed json is due to badly written js in the drupal module

From stackoverflow
  • What code are you using to POST the data? Make sure you're using something like json2.js.

    Steven Noble : I should check. I'm using drupal's json_service modulue.
    Steven Noble : Ah, this seems to be the crux of the problem. A badly written json encoder
  • This would be a good way to handle JSON where you can't predict whether there's extraneous commas:

    function json_decode_($json_string) {
        $json_string = preg_replace('/,(\s*)}/s', '$1}', $json_string);
        return json_decode($json_string);
    }
    

    Note, this is untested, but I think it should work.

0 comments:

Post a Comment