如何修复此未转义的无效 JSON?(在菲律宾语中)



我的网站应该处理来自POST的数据,其中POST文档的正文是JSON对象。不幸的是,某些 POST 的正文如下所示,例如:

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

当然这不是有效的 JSON,它应该看起来像这样:

{ "FromAddress": "user@gmail.com", "Subject": "Note to self", "BodyPlain": "nthisnisnanmultilinentestnwhat about these? \n\nn.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。

它需要能够正确转义任何其他麻烦的输入。

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

这个简单的单行固定功能是str_replace() .查看实际操作:

$bad_json = <<< END
{ "FromAddress": "user@gmail.com", "Subject": "Note to self", "BodyPlain": "
this
is
a
multiline
test
what about these? nn
.
" }
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

最新更新