php json_decode fails without quotes on key

后端 未结 8 1909
故里飘歌
故里飘歌 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

    This worked for me, using regex replace '/\s(\w+)\s/i'

    $json =  file_get_contents("php://input"); // or whatever json data
    $json = preg_replace('/\s(\w+)\s/i', '"$1"', $json);
    $json = json_decode($json, true);
    
    0 讨论(0)
  • 2020-12-06 07:17

    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.

    0 讨论(0)
提交回复
热议问题