简体   繁体   English

使用 JQ 向 json 文件添加更多字段

[英]Add more field to json file using JQ

I would like to fill a JSON file, that is still empty with the below values using JQ.我想使用 JQ 填充一个 JSON 文件,该文件仍然为空,并带有以下值。

I tried this code:我试过这段代码:

 echo '{"Name": "FileName", "Size": "FileSize", "Action": "Action taken"}' | jq file.json

But it failed:但它失败了:

jq: error: clear/0 is not defined at, line 1: clear.json jq: 1 compile error jq: error: clear/0 is not defined at, line 1: clear.json jq: 1 compile error

 [
   // Data should goes here
 ]

Expecting result:预期结果:

 [
      {
       "Name": "FileName",
       "Size": "FileSize",
       "Action": "Action taken",
      },

      // and so on
 ]

Thanks in advance提前致谢

I'm having trouble understanding the details of your question, but it sounds like you have:我无法理解您的问题的详细信息,但听起来您有:

  • A JSON string representing an object, eg '{"foo": "bar"}'代表 object 的 JSON 字符串,例如'{"foo": "bar"}'
  • A JSON file that contains either一个 JSON 文件,其中包含
    • Nothing (the file is empty and therefore not valid JSON)无(文件为空,因此 JSON 无效)
    • A JSON array, eg [{"a": "b"}, {"c": "d"}]一个 JSON 数组,例如[{"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. 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.

The easiest way to do this is to first make sure the file contains valid JSON by writing an empty array to if it's empty, and then unconditionally append to that list:最简单的方法是首先确保文件包含有效的 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"

If you start with an empty file (or no file), after successfully running, the file would contain this:如果您从一个空文件(或没有文件)开始,成功运行后,该文件将包含以下内容:

[
  {
    "Name": "FileName",
    "Size": "FileSize",
    "Action": "Action taken"
  }
]

If you run it one more time, it would contain this:如果再运行一次,它将包含以下内容:

[
  {
    "Name": "FileName",
    "Size": "FileSize",
    "Action": "Action taken"
  },
  {
    "Name": "FileName",
    "Size": "FileSize",
    "Action": "Action taken"
  }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM