从无效的 json 中删除尾随逗号(使其有效)

Som*_*omy 5 text-processing json

假设我有一个文件如下

{
    "fruit": "Apple",
}
Run Code Online (Sandbox Code Playgroud)

我想删除行尾的逗号,当且仅当下一行包含“}”。所以,输出将是:

{
    "fruit": "Apple"
}
Run Code Online (Sandbox Code Playgroud)

但是,如果文件如下。我不想做任何改变。由于,s 后面没有 a}

{
    "fruit": "Apple",
    "size": "Large",
    "color": "Red"
}
Run Code Online (Sandbox Code Playgroud)

任何带有 sed 的东西都会很棒。

Kus*_*nda 7

造成这个问题的原因在于 JSON 格式不关心键或数据中不出现的空格。所以,

{ "key": "data" }
Run Code Online (Sandbox Code Playgroud)

是相同的

{ "key":
"data"
}
Run Code Online (Sandbox Code Playgroud)

如果添加“损坏”JSON 文件的可能性,例如

{ "key":
"data", }
Run Code Online (Sandbox Code Playgroud)

除了知道如何在解析数据时放松 JSON 格式的限制的 JSON 解析器之外,使用其他任何东西来正确解析文档变得非常困难。

PerlJSON模块可以做到这一点,并且还可以漂亮地打印结果:

$ cat file.json
{
    "fruit": "Apple",
}
Run Code Online (Sandbox Code Playgroud)
$ perl -MJSON -e '@text=(<>);print to_json(from_json("@text", {relaxed=>1}), {pretty=>1})' file.json
{
   "fruit" : "Apple"
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们将整个文本文档读入数组中@text。然后,我们在放松解析的同时对其进行解码(这使得 JSON 文档可以在前面有逗号},并且]还可以包含#注释)。然后我们立即将生成的 Perl 数据结构再次编码为 JSON 并打印它。

另一个例子:

$ cat file.json
{
    "fruit": "Apple",   # a comment
    "stuff": [1, 2, 3,],
}
Run Code Online (Sandbox Code Playgroud)
$ perl -MJSON -e '@text=(<>);print to_json(from_json("@text", {relaxed=>1}), {pretty=>1})' file.json
{
   "fruit" : "Apple",
   "stuff" : [
      1,
      2,
      3
   ]
}
Run Code Online (Sandbox Code Playgroud)

没有漂亮的印刷:

$ perl -MJSON -e '@text=(<>);print to_json(from_json("@text", {relaxed=>1}))' file.json
{"fruit":"Apple","stuff":[1,2,3]}
Run Code Online (Sandbox Code Playgroud)

(输出末尾没有换行符)

对于非常大的文档,您可能需要使用模块的增量解析功能并编写适当的转换脚本。


小智 5

sed -i.bak ':begin;$!N;s/,\n}/\n}/g;tbegin;P;D' FILE
Run Code Online (Sandbox Code Playgroud)

sed -i.bak= 创建原始文件的备份,然后将更改应用于该文件

':begin;$!N;s/,\n}/\n}/g;tbegin;P;D'= 以 结尾的任何内容后跟换行符和 }。删除上一行的,

FILE= 您要更改的文件