我有一串需要 json_decode 的 json 对象,但 json 格式无效,因为它没有双引号(或任何引号)。有些文本带有逗号,这使得将其格式化为 json 变得更加困难。
这是我得到的字符串:
[{2:,0:1,1:Rodapi\u00e9s 1-a, 2-a, bloque 6}]
这是我需要成为有效 JSON 的格式:
[{"2":"","0":"1","1":"Rodapi\u00e9s 1-a, 2-a, bloque 6"}]
我有添加字符串的代码,但不适用于包含逗号的文本:
$str = str_replace('{', '{"', $str);
$str = str_replace(':', '":"', $str);
$str = str_replace(',', '","', $str);
$str = str_replace('}', '"}', $str);
$str = str_replace('}","{', '},{', $str);
这就是我得到的:
[{"2":"","0":"1","1":"Rodapi\u00e9s 1-a"," 2-a"," bloque 6"}]
用字符串键替换数字键
$str = preg_replace('/(\d+):/', '"$1":', $str);
在值周围添加双引号
$str = preg_replace('/(":)(.*?)(,"|})/', '$1"$2"$3', $str);
如果你的键是数字,那么下面的正则表达式应该能满足你的需要:
(?<=[{,])\s*(\d+)\s*:(.*?)(?=}|,\s*\d+\s*:)
它匹配:
(?<=[{,])
:向后看 {
或 ,
\s*(\d+)\s*:
:一个数字键,可能被空格包围,在组 1(.*?)
:最小数量的字符,在第 2 组中捕获,受以下先行(?=}|,\s*\d+\s*:)
:先行查找 }
或逗号后跟数字键值在 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);
输出:
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
)
)