php json_decode fails without quotes on key

后端 未结 8 1930
故里飘歌
故里飘歌 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 06:52

    To avoid that double quotes are inserted in places where they shouldn't, you should skip those quoted strings in this manipulation.

    For instance, if you have this JavaScript object literal in a string:

    {
       dt:"2016-10-22T09:13:20",
       "x:y":false
    }
    

    ... then care must be taken not to have 22T09: change into "22T09":. Also the already quoted key, "x:y" should stay unaltered.

    You could use this regular expression for achieving that:

    preg_replace('/("(.*?)"|(\w+))(\s*:\s*(".*?"|.))/s', '"$2$3"$4', $text);
    

    Other issues

    JavaScript object literals allow numeric constants with left-padded zeroes, like 001, and/or with the unary + sign, which are neither allowed in JSON. To remove those offending characters also, you could use this extended version:

    preg_replace('/("(.*?)"|(\w+))(\s*:\s*)\+?(0+(?=\d))?(".*?"|.)/s', '"$2$3"$4$6', $text);
    

提交回复
热议问题