使用PHP的无效JSON解析 [英] Invalid JSON parsing using PHP
本文介绍了使用PHP的无效JSON解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要提取的JSON提要是无效的JSON.它完全缺少引号.我已经尝试了一些方法,例如explode()
和str_replace()
,以使该字符串看起来更像有效的JSON,但其中包含关联的JSON字符串,通常会使它搞砸.
I'm pulling a JSON feed that is invalid JSON. It's missing quotes entirely. I've tried a few things, like explode()
and str_replace()
, to get the string looking a little bit more like valid JSON, but with an associate JSON string inside, it generally gets screwed up.
这是一个例子:
id:43015,name:'John Doe',level:15,systems:[{t:6,glr:1242,n:'server',s:185,c:9}],classs:0,subclass:5
有没有适用于php的JSON解析器,可以像这样处理无效的JSON?
Are there any JSON parsers for php out there that can handle invalid JSON like this?
我正在尝试在此字符串上使用json_decode()
.它什么也不返回.
I'm trying to use json_decode()
on this string. It returns nothing.
推荐答案
- 所有引号应为双引号
"
,而不是单引号'
. - 所有键都应加引号.
- 整个元素应该是一个对象.
- All the quotes should be double quotes
"
and not single quotes'
. - All the keys should be quoted.
- The whole element should be an object.
function my_json_decode($s) {
$s = str_replace(
array('"', "'"),
array('\"', '"'),
$s
);
$s = preg_replace('/(\w+):/i', '"\1":', $s);
return json_decode(sprintf('{%s}', $s));
}
这篇关于使用PHP的无效JSON解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文