在PHP中处理格式错误的JSON [英] Handling malformed JSON in PHP
问题描述
我正在尝试编写一个php脚本来处理来自Web服务的数据,该服务以字符串形式传递"json".问题是字符串不是真正的json;它是javascript.具体来说,虽然变量是带引号的,但键不带引号.示例(实际数据更长,更复杂):
I'm trying to write a php script that handles data from a webservice that delivers "json" as a string. The problem is the string isn't really json; it's javascript. Specifically, the keys are not quoted, although the variables are. Example (the actual data is much longer and more complicated):
{desc:'User defined payload'}
如 php手册所述,json_decode()正确地无法解释该字符串.
As described by the php manual, json_decode() correctly fails to interpret this string.
我的问题是,如何在php中成功解释这样的字符串?
My question is, how can I successfully interpret a string like this in php?
我能想到的唯一解决方案是编写一些可修复语法的正则表达式,但随后我会遇到两个问题.
The only solution I can think of is to write some regular expressions that fix the syntax, but then I'd have two problems.
编辑
Hadvig关于使用Services_JSON pear模块的建议有效,并且看起来像是通用解决方案.安装模块后,我的代码如下所示:
Hadvig's suggestion of using the Services_JSON pear module worked, and looks like a general solution. Once I had the module installed, my code looked like this:
require_once 'PEAR.php';
require_once 'Services/JSON.php';
$Services_JSON = new Services_JSON();
$data = $Services_JSON->decode($malformed_json);
不幸的是,这很慢.解释整个字符串(〜400,000个字符)需要> 36秒!使用正则表达式来固定引号,然后使用json_decode花费了约0.04秒.这是我用的:
Unfortunately, this is SLOW. To interpret the whole string (~400,000 chars) took > 36 seconds! Using a regular expression to fix the quotes and then using json_decode took ~0.04 seconds. Here's what I used:
// fix single quotes
$s = str_replace("'", '"', $malformed_json);
// fix unquoted keys
$valid_json = preg_replace('/([{\[,])\s*([a-zA-Z0-9_]+?):/', '$1"$2":', $s);
$data = json_decode($valid_json);
当然,如果数据包含任何引号,方括号或逗号,则此操作将中断.
Of course, this will break if the data contains any quotes, brackets, or commas.
推荐答案
好.尝试使用这个. http://pear.php.net/pepr/pepr-proposal -show.php?id = 198 我只是检查您的字符串
Ok. try to use this. http://pear.php.net/pepr/pepr-proposal-show.php?id=198 I just check your string
这篇关于在PHP中处理格式错误的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!