php json_decode fails without quotes on key

Viewed 16836

I have json data represented like this

{key:"value"}

(no quotes arround key...)

I want to translate it to an associative array.

PHP's json_decode returns null

How can I add the quotes around the key?? thanks...

8 Answers

Please do not use regexps to do this! JSON grammar cannot be correctly parsed this way by definition. You will open yourself to a ton of future bugs.

I recommend using a YAML parser, because YAML is a superset of JSON and allows unquoted literals at the same time.

Symfony YAML component works great.

There will be a performance penalty in comparison to json_decode which is implemented natively.

DON'T USE REGEX.

REGEX is totally not recommended for such cases, don't use that for parsing such data. If you have a simple goals and want to avoid the stable PEAR package, then you might try JSON-php library (but no-longer maintained).

1) Get JSON.phps file from here and rename to .php and replace constructor function names to __construct.

2) usage:

$content = '{myKey:"valueeeee"}';

include(__DIR__.'/JSON.php'); 
$this->json = new Services_JSON( SERVICES_JSON_LOOSE_TYPE );  // to return objects instead of Associative array, remove the argument
var_dump( $this->json->decode($content)  );
Related