如何在PHP中修复格式错误的JSON? [英] How to fix badly formatted JSON in PHP?

查看:194
本文介绍了如何在PHP中修复格式错误的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在获取JSON格式和唯一可用格式的数据提要.在PHP中,我正在使用json_decode解码JSON,但此操作已中断,并且我发现JSON是在某些地方生成的,其昵称用双引号引起来.我使用以下方法验证了这一点: http://jsonformatter.curiousconcept.com

I'm getting a data feed which is in JSON format and the only available format. In PHP, I'm using json_decode to decode the JSON, but it was breaking, and I found out that the JSON was generated in some places with double quotes in a person's nick name. I verified this using: http://jsonformatter.curiousconcept.com

我无法控制数据的创建,但是当这种格式出现时,我必须处理它.解析后的数据将被放入MySQL TABLE.

I don't have control over the creation of the data, but I have to deal with this broken format when it occurs. This data after it's parsed will be put into a MySQL TABLE.

例如:

"contact1": "David "Dave" Letterman",

json_decode将返回NULL.如果我手动保存文件,然后将其更改为戴夫(Dave)昵称的单引号,则一切正常.

json_decode would return a NULL. If I manually saved the file, and changed it to single quotes around the nickname of Dave, then everything worked.

$json_string = file_get_contents($json_download);
$json_array = json_decode($json_string, true);

在被json_decode处理之前,如何解决json_string中损坏的JSON格式? 要对文件进行预处理,对昵称的双引号加反斜杠,应该怎么做?还是将它们更改为单引号?在MySQL中像这样存储双引号甚至是个好主意吗?

How do I fix the broken JSON format in json_string before it gets processed by json_decode? What should be done to pre-process the file, backslash the double quotes of the nickname? Or change them to single quotes? Is it even a good idea to store double quotes like this in MySQL?

我不知道每个数据提要何时会发生这种情况,因此我不想仅检查contact1是否具有内部双引号来修复它们. PHP中是否有办法采用上述示例中的一行,并在冒号之后的所有内容(除外部双引号之外)都反斜杠?谢谢!

I don't know when this might occur with each data feed, so I don't want to just check for contact1 if it has inner double quotes to fix them. Is there a way in PHP to take a line such as the above example, and backslash everything after the colon except the outer double quotes? Thanks!

这是tftd提供的正确代码:

This is the correct code for as provided by tftd:

<?php
// This:
// "contact1": "David "Dave" Letterman",
// Needs to look like this to be decoded by JSON:
// "contact1": "David \"Dave\" Letterman",

$data ='"contact1": "David "Dave" Letterman",';
function replace($match){
    $key = trim($match[1]);
    $val = trim($match[2]);

    if($val[0] == '"')
        $val = '"'.addslashes(substr($val, 1, -1)).'"';
    else if($val[0] == "'")
        $val = "'".addslashes(substr($val, 1, -1))."'";

    return $key.": ".$val;
}
$preg = preg_replace_callback("#([^{:]*):([^,}]*)#i",'replace',$data);
var_dump($preg);
$json_array = json_decode($preg);
var_dump($json_array);
echo $json_array . "\n";
echo $preg . "\n";
?>

以下是输出:

string(39) ""contact1": "David \"Dave\" Letterman","
NULL

"contact1": "David \"Dave\" Letterman",

推荐答案

正如其他人已经指出的那样,最好将JSON格式的问题告知客户.要求他们将错误报告发送给原始开发者/公司,以便他们进行修复.如果他/他们无法解决-请提供您的解决方案.您只需在json_encode字符串之前先addslashes字符串.

As others have already pointed out, it's best if you tell your client for the problem with the JSON formatting. Ask them to send a bugreport to the original developer/company so they could fix it. If he/they can't fix it - then offer your solution. You simply need to addslashes the string before you json_encode it.

如果由于某种原因最终不得不格式化,则此方法可能对您有用:

If for some reason you end up having to fix the formatting, here is a way that might work for you:

$data = '"contact1": "David "Dave" Letterman", "contact2": "Peter "Robert" Smith",{\'test\': \'working "something"\'}';
function replace($match){
    $key = trim($match[1]);
    $val = trim($match[2]);

    if($val[0] == '"')
        $val = '"'.addslashes(substr($val, 1, -1)).'"';
    else if($val[0] == "'")
        $val = "'".addslashes(substr($val, 1, -1))."'";

    return $key.": ".$val;
}
$preg = preg_replace_callback("#([^{:]*):([^,}]*)#i",'replace',$data);
var_dump($preg);
// string '"contact1": "David \"Dave\" Letterman", "contact2": "Peter \"Robert\" Smith",{'test': 'working \"something\"'}' (length=110)

请记住,如果有人再次弄乱json格式,这可能会中断.

Keep in mind this may break if somebody messes with the json format again.

这篇关于如何在PHP中修复格式错误的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆