提问人:LauraEld 提问时间:5/3/2023 更新时间:5/4/2023 访问量:77
PHP 正则表达式格式化不带引号的 json 字符串
PHP regex to format json string without quotes
问:
我需要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"}]
答:
2赞
Maxim Kaminskiy
5/3/2023
#1
将数字键替换为字符串键
$str = preg_replace('/(\d+):/', '"$1":', $str);
在值两边添加双引号
$str = preg_replace('/(":)(.*?)(,"|})/', '$1"$2"$3', $str);
1赞
Nick
5/4/2023
#2
如果您的键是数字,则以下正则表达式应满足您的需求:
(?<=[{,])\s*(\d+)\s*:(.*?)(?=}|,\s*\d+\s*:)
它匹配:
(?<=[{,])
:查找 OR{
,
\s*(\d+)\s*:
:在组 1 中捕获的数字键,可能用空格括起来(.*?)
:最少数量的字符,在第 2 组中捕获,但须遵守以下预测(?=}|,\s*\d+\s*:)
:A 或逗号后跟数字键值的展望}
在 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
)
)
评论
the json format is not valid
...这意味着这不是真的。 会更准确。或者,也许。I have a string of json objects
I have a string
I have a string which looks a bit like json
(\d+):((?:[^,\d}\]]+|,(?!\h*\d+:)|\d+(?!:))*)
和“$1”:“$2”
就可以了(PHP 演示)。