如何修复这个无法转义的无效JSON? (在PHP中)

时间:2017-03-23 05:27:12

标签: php json escaping

我的网站应该处理来自POST的数据,其中POST文档的主体是JSON对象。不幸的是,一些POST的主体看起来像这样,例如:

{ "FromAddress": "user@gmail.com", "Subject": "Note to self", "BodyPlain": "
this
is
a
multiline
test
what about these? \n\n
.
" }

当然这不是有效的JSON,它应该是这样的:

{ "FromAddress": "user@gmail.com", "Subject": "Note to self", "BodyPlain": "\nthis\nis\na\nmultiline\ntest\nwhat about these? \\n\\n\n.\n" }

处理这种情况最简单的方法是什么?我希望得到这样的解决方案:

if ( $_SERVER['REQUEST_METHOD']=='POST' ) {
    $in = file_get_contents("php://input");
    $in = some_escape_function($in);  // is there a simple one-liner that can go here?
    $indata = json_decode($in,true);
}

如果不修复它,json_decode将只返回NULL,因为输入是无效的JSON。

它需要能够正确地逃避任何其他麻烦的输入。

当然,最好的解决方案是首先正确地逃避它。我正在寻找即时解决方法以及如何建议客户正确逃离。

1 个答案:

答案 0 :(得分:0)

简单的单行修复功能是str_replace()。看到它在行动:

$bad_json = <<< END
{ "FromAddress": "user@gmail.com", "Subject": "Note to self", "BodyPlain": "
this
is
a
multiline
test
what about these? \n\n
.
" }
END
;

print_r(
    json_decode(
        str_replace("\n", "\\n", 
            trim($bad_json)
        ), TRUE
    )
);
echo("===================\n");
echo(json_last_error_msg());

输出结果为:

Array
(
    [FromAddress] => user@gmail.com
    [Subject] => Note to self
    [BodyPlain] =>
this
is
a
multiline
test
what about these?


.

)
===================
No error