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

如何使用PHP解码带有注释的JSON文件?,php,json,regex,comments,Php,Json,Regex,Comments,在一项任务中,我必须在JSON文件中编写注释,并使用PHP对其进行解码。我分享它。也许这对其他人有帮助。正则表达式很难处理。删除带有正则表达式的注释 $jsonStringWithComments = file_get_contents ( "jsonFileWithComments.json" ); $pattern = '/(((?<!http:|https:)\/\/.*|(\/\*)([\S\s]*?)(\*\/)))/im'; $decodedObject = json_deco

在一项任务中,我必须在JSON文件中编写注释,并使用PHP对其进行解码。我分享它。也许这对其他人有帮助。正则表达式很难处理。

删除带有正则表达式的注释

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

当然,如果您将注释添加到JSON文件中,它将不再是JSON文件,因为注释不是JSON规范的一部分!?对没错。变成了别的东西。它不再是json了,所以这有点像是说,当一个C程序中有几行COBOL代码时,我该如何编译它!JSON是一种机器到机器的数据传输格式,注释在其中没有位置。我的意思是,这是一个需要解决的合法问题——确实有一些文件是人们想要成为JSON的,其中包含注释。但也就是说,这不是一个以前没有被回答过的问题,所以发布和回答你自己的问题看起来就像你在寻找容易的名声。这不是发布教程的网站。
{
  "lorem": "ipsum",
  "dolor":/* inline comment */ "sit amet",
  "consectetur": "adipiscing",
/*
multi
line
comment
*/  
  "Pellentesque": "ultrices",
//single line comment  
  "lectus": "nec",
  "elit": "dictum",
  "url": "http://example.com"
}