首页 > 解决方案 > 使用 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
 ]

提前致谢

标签: jsonbashjq

解决方案


我无法理解您的问题的详细信息,但听起来您有:

  • 表示对象的 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"
  }
]

推荐阅读