Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php json_decode fails without quotes on key

Tags:

json

php

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

like image 507
Bar Avatar asked Aug 04 '11 12:08

Bar


People also ask

Why is json_decode returning null?

null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting limit.

What json_decode () function will return?

Syntax. The json_decode() function can take a JSON encoded string and convert into a PHP variable. The json_decode() function can return a value encoded in JSON in appropriate PHP type. The values true, false, and null is returned as TRUE, FALSE, and NULL respectively.

What is the use of json_decode in PHP?

The json_decode() function is used to decode or convert a JSON object to a PHP object.


1 Answers

You can either fix the JSON at the source so that it returns a valid JSON structure, or you can manually add quotes around the keys.

This answer to a similar question has an example of how to do that:

function my_json_decode($s) {
    $s = str_replace(
        array('"',  "'"),
        array('\"', '"'),
        $s
    );
    $s = preg_replace('/(\w+):/i', '"\1":', $s);
    return json_decode(sprintf('{%s}', $s));
}
like image 59
Intelekshual Avatar answered Oct 10 '22 04:10

Intelekshual