json - 使用 JQ 向 json 文件添加更多字段
问题描述
我想使用 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
]
提前致谢
解决方案
我无法理解您的问题的详细信息,但听起来您有:
- 表示对象的 JSON 字符串,例如
'{"foo": "bar"}'
- 一个 JSON 文件,其中包含
- 无(文件为空,因此 JSON 无效)
- 一个 JSON 数组,例如
[{"a": "b"}, {"c": "d"}]
并且您想将 JSON 对象附加到现有数组,或者如果文件为空,则创建一个新数组,将该对象作为其自己的元素。
最简单的方法是首先确保文件包含有效的 JSON,方法是写入一个空数组到它是否为空,然后无条件地附加到该列表:
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"
}
]
推荐阅读
- security - 如何在 OWASP 测试中为 POST、PUT、PATCH 方法生成数据?
- javascript - 添加在使用 javascript 加载网站时不需要可见的大部分 HTML 是否是一种不好的做法?
- pdf - Puppeteer PDF,页脚和内容在同一行?
- php - PHP中的数组比较和重新排序
- azure-ad-b2c - Azure Active Directory B2C - IE 问题
- r - caret::train 包中 type = 'prob' 参数的问题
- loops - ASP.Net Core MVC 更新模型
- typescript - 如何在单击按钮时在 nginx 中的多个页面中重定向
- react-native - React Native Production App 在异常时显示空白屏幕
- list - 从序言中的其他列表创建第二个列表