I have a string of json objects I need to json_decode but the json format is not valid because it doesn’t have double quotes (or any quote). And some texts have commas what makes it more difficult to format as json.
This is the string I get:
[{2:,0:1,1:Rodapiu00e9s 1-a, 2-a, bloque 6}]
This is the format I need to be a valid JSON:
[{"2":"","0":"1","1":"Rodapiu00e9s 1-a, 2-a, bloque 6"}]
I have a code to add strings but doesn’t work with texts containing commas:
$str = str_replace('{', '{"', $str);
$str = str_replace(':', '":"', $str);
$str = str_replace(',', '","', $str);
$str = str_replace('}', '"}', $str);
$str = str_replace('}","{', '},{', $str);
This is what I get:
[{"2":"","0":"1","1":"Rodapiu00e9s 1-a"," 2-a"," bloque 6"}]
2
Answers
Replace numeric keys with string keys
Add double quotes around values
If your keys are numeric, then the following regex should meet your needs:
It matches:
(?<=[{,])
: lookbehind for{
or,
s*(d+)s*:
: a numeric key, possibly surrounded by spaces, captured in group 1(.*?)
: a minimal number of characters, captured in group 2, subject to the following lookahead(?=}|,s*d+s*:)
: a lookahead for either a}
or a comma followed by a numeric key valueDemo on regex101
In PHP:
Output:
Demo on 3v4l.org