我的文件夹和子文件夹中有几个 json 文件,我只想打印其中的 3 个字段。我对所有 json 文件使用 for 循环,但这里为了简单起见,下面的输入代表 3 个 json 文件。对于每个文件,我只想在每个文件中至少出现一个“Dmo = Path”时打印“文件名”和“值”。当文件不包含“Dmo = Path”块时,则仅打印文件名。
{
"Filename": "File_213",
"Date": "2024-4-30",
"Blocks": [
{
"Dmo": "WW",
"Value": "23",
"String": "",
},
{
"Dmo": "Path",
"Value": "/Files/2024/abd",
"String": "",
},
{
"Dmo": "Path",
"Value": "/Files/2024/Ndew",
"String": "",
}
]
}
{
"Filename": "File_4",
"Date": "2024-4-30",
"Blocks": [
{
"Dmo": "WW",
"Value": "45",
"String": "",
}
]
}
{
"Filename": "File_43",
"Date": "2024-4-30",
"Blocks": [
{
"Dmo": "Path",
"Value": "/Files/2023/Roi2",
"String": "",
}
}
]
}
我当前的代码和当前输出如下
$ awk '/"Filename":/{fnm=$2}
/Dmo/{dmo=$2}
/Value/ {
val=$2;
if (dmo != "")
print fnm,val
else
print fnm
fnm=""; dmo="";val=""}' input
"File_213", "23",
"/Files/2024/abd",
"/Files/2024/Ndew",
"File_4", "45",
"File_43", "/Files/2023/Roi2",
我的预期输出是:
File_213, /Files/2024/abd
File_213, /Files/2024/Ndew
File_4
File_43, /Files/2023/Roi2
jq
比 awk
更好地处理 JSON 文件。
for j in *.json ; do
jq -r '[.Filename, [.Blocks[] | select(.Dmo=="Path")]] as [$f, $p]
| if $p[0]
then ($p[].Value | [$f, .])
else [$f]
end | @csv' < $"j" ; done
输出:
"File_213","/Files/2024/abd"
"File_213","/Files/2024/Ndew"
"File_4"
"File_43","/Files/2023/Roi2"