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:Rodapi\u00e9s 1-a, 2-a, bloque 6}]
This is the format I need to be a valid JSON:
[{"2":"","0":"1","1":"Rodapi\u00e9s 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":"Rodapi\u00e9s 1-a"," 2-a"," bloque 6"}]
If your keys are numeric, then the following regex should meet your needs:
(?<=[{,])\s*(\d+)\s*:(.*?)(?=}|,\s*\d+\s*:)
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 valueIn PHP:
$str = '[{2:,0:1,1:Rodapi\u00e9s 1-a, 2-a, bloque 6},
{4:x, y, z,0 :111, 3:some random text},{5:a45:bc,def}]';
$str = preg_replace('/(?<=[{,])\s*(\d+)\s*:(.*?)(?=}|,\s*\d+\s*:)/', '"$1":"$2"', $str);
$obj = json_decode($str);
print_r($obj);
Output:
Array
(
[0] => stdClass Object
(
[2] =>
[0] => 1
[1] => Rodapiés 1-a, 2-a, bloque 6
)
[1] => stdClass Object
(
[4] => x, y, z
[0] => 111
[3] => some random text
)
[2] => stdClass Object
(
[5] => a45:bc,def
)
)