php json_decode fails without quotes on key

后端 未结 8 1931
故里飘歌
故里飘歌 2020-12-06 06:26

I have json data represented like this

{key:\"value\"}

(no quotes arround key...)

I want to translate it to an associative array.

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 07:09

    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));
    }
    

提交回复
热议问题