I have json data represented like this
{key:\"value\"}
(no quotes arround key...)
I want to translate it to an associative array.>
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);
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);