如何使用PHP解码带注释的JSON文件?

时间:2018-09-07 16:37:25

标签: php json regex comments

在一项任务中,我必须在 JSON 文件中编写注释,然后使用 PHP 对其进行解码。我分享。也许它可以帮助别人。正则表达式很难。

1 个答案:

答案 0 :(得分:-2)

删除带有正则表达式的评论

IdentityUserLogin

此正则表达式可以捕获“单行”注释,在斜杠星号/ *和星号斜杠* /之间以双斜杠//或“多行”注释。

有了它,您可以像下面这样解析JSON:

$jsonStringWithComments = file_get_contents ( "jsonFileWithComments.json" );
$pattern = '/(((?<!http:|https:)\/\/.*|(\/\*)([\S\s]*?)(\*\/)))/im';
$decodedObject = json_decode ( preg_replace ( $pattern, '', $jsonStringWithComments ) );