使用正则表达式删除JSON注释(字符串中的注释除外)



我想删除JSON对象中的所有注释,字符串中的注释除外。例如:

{
//Remove this comment
"Command": "storeSystemConfig",
"SystemId": "1234", //Remove this comment
/*Remove this and the empty line above and below*/
/*This can be removed but not what behind here =>*/ "TestParam": "Hello",
"TestString": "Do not revome this comment /*don not remove*/ and also this one: //Test comment"
}

我现在使用以下正则表达式:

#(\*([^*]|[rn]|(*+([^*/]|[rn])))**+/)|([st]/.*)|(^/.*)#

但不幸的是,这个表达式还删除了"TestString"参数中的注释。在这里,您可以看到这个表达式是如何处理JSON数据的:https://regex101.com/r/65VL8v/1这里是我在工作环境中的PHP源代码:https://ideone.com/F4v20p

这是我的尝试:

<?php

$json_origen = <<<'JSON'
{
//Remove this comment
"Command": "storeSystemConfig", /*1234*/
"SystemId": "1234", //Remove this comment

/*Remove this and the 
empty line above and below*/

/*This can be removed but not what behind here =>*/ "TestParam": "Hello",
"TestString": "DNR this comment /*don not remove*/ and also this one: //Test comment" /*4321*/ //1234
}
JSON;

//Remove lines with only single line comments
$json = preg_replace("/[nr]s*//.*/", "", $json_origen);
//Remove all lines with only multi line comments
$json = preg_replace("/(?<=[nr])s*/*(.[nr]?)*?*/s*?/", "", $json);
//Remove lines multi line comments at the end
$json = preg_replace("/(".+?(?<!\\)"s*,?)s*/*(.[nr]?)*?*/s*?/", "\1", $json);
//Remove comment at the end of a line
$json = preg_replace("/(".+?(?<!\\)"s*,?)s*//.*?(?=[nr])/", '\1', $json);
//Remove empty lines
$json = preg_replace('/ns*n/', "n", $json);

echo($json);

?>

在一个正常的JSON语句之后还有多行注释的问题,但我现在必须写我的大学考试了,哈哈,我很快就会更新这个答案。不过,对于示例输入,这应该有效。

让我知道JSON中是否存在任何其他无关的情况


编辑1:使用负查找(?<!\\)解决了一个值可能包含双引号的问题,因此转义的双引号不计算

EDIT 2:修复了我谈到的正常json语句后的多行注释问题。

第3版:我提供了答案,但没有提供详细的解决方案,所以我在这里使用的概念是正面和负面的lookbehinds和lookahead。此外,我有使用[nr]而不仅仅是n的习惯,因为其他问题可能会发生

第4版:存在一个问题,即如果多行注释位于同一行,则不会删除多行注释之后的单行注释。通过简单地更改正则表达式删除的顺序来修复此问题。

EDIT 5:修复了json语句发布后的多行注释,只需要在语句后检查可能的逗号

最新更新