[英]Add more field to json file using JQ
我想使用 JQ 填充一个 JSON 文件,该文件仍然为空,并带有以下值。
我试过这段代码:
echo '{"Name": "FileName", "Size": "FileSize", "Action": "Action taken"}' | jq file.json
但它失败了:
jq: error: clear/0 is not defined at, line 1: clear.json jq: 1 compile error
[
// Data should goes here
]
预期结果:
[
{
"Name": "FileName",
"Size": "FileSize",
"Action": "Action taken",
},
// and so on
]
提前致谢
我无法理解您的问题的详细信息,但听起来您有:
'{"foo": "bar"}'
[{"a": "b"}, {"c": "d"}]
And you want to append the JSON object to the existing array, or if the file is empty, create a new array with the object as its own element.
最简单的方法是首先确保文件包含有效的 JSON,如果它是空的,则写入一个空数组,然后无条件地将 append 写入该列表:
file='myfile.json'
object='{"Name": "FileName", "Size": "FileSize", "Action": "Action taken"}'
# Check if file is empty
if ! [ -s "$file" ]
then
# It is. Write an empty array to it
echo '[]' > "$file"
fi
# Read from the file, append the object, write to a temporary file
jq --argjson x "$object" '. += [$x]' < "$file" > tmp.json
# Overwrite the original file with the temporary one
mv tmp.json "$file"
如果您从一个空文件(或没有文件)开始,成功运行后,该文件将包含以下内容:
[
{
"Name": "FileName",
"Size": "FileSize",
"Action": "Action taken"
}
]
如果再运行一次,它将包含以下内容:
[
{
"Name": "FileName",
"Size": "FileSize",
"Action": "Action taken"
},
{
"Name": "FileName",
"Size": "FileSize",
"Action": "Action taken"
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.