Immo Broker
Immo Broker

Reputation: 65

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.

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

 [
   // Data should goes here
 ]

Expecting result:

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

      // and so on
 ]

Thanks in advance

Upvotes: 1

Views: 2195

Answers (1)

that other guy
that other guy

Reputation: 123680

I'm having trouble understanding the details of your question, but it sounds like you have:

  • A JSON string representing an object, e.g. '{"foo": "bar"}'
  • A JSON file that contains either
    • Nothing (the file is empty and therefore not valid JSON)
    • A JSON array, e.g. [{"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.

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:

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"
  }
]

Upvotes: 2

Related Questions