Home > database >  iterating through JSON files adding properties to each with jq
iterating through JSON files adding properties to each with jq

Time:12-29

I am attempting to iterate through all my JSON files and add properties but I am relatively new jq.

here is what I am attempting:

find hashlips_art_engine/build -type f -name '*.json' | jq '.   {
  "creators": [
    {
      "address": "4iUFmB3H3RZGRrtuWhCMtkXBT51iCUnX8UV7R8rChJsU",
      "share": 10
    },
    {
      "address": "2JApg1AXvo1Xvrk3vs4vp3AwamxQ1DHmqwKwWZTikS9w",
      "share": 45
    },
    {
      "address": "Zdda4JtApaPs47Lxs1TBKTjh1ZH2cptjxXMwrbx1CWW",
      "share": 45
    }
  ]
}'

However this is returning an error:

parse error: Invalid numeric literal at line 2, column 0

I have around 10,000 JSON files that I need to iterate over and add

{
  "creators": [
    {
      "address": "4iUFmB3H3RZGRrtuWhCMtkXBT51iCUnX8UV7R8rChJsU",
      "share": 10
    },
    {
      "address": "2JApg1AXvo1Xvrk3vs4vp3AwamxQ1DHmqwKwWZTikS9w",
      "share": 45
    },
    {
      "address": "Zdda4JtApaPs47Lxs1TBKTjh1ZH2cptjxXMwrbx1CWW",
      "share": 45
    }
  ]
}

to, is this possible or am I barking up the wrong tree on this?

thanks for your assistance with this, I have been searching the web for several hours now but either my terminology is incorrect or there isn't much out there regarding this issue.

CodePudding user response:

The problem is that you are piping the filenames to jq rather than making the contents available to jq.

Most likely you could use the following approach, e.g. if you want the augmented contents of each file to be handled separately:

find ... | while read f ; do jq ... "$f" ; done

An alternative that might be relevant would be:

jq ... $(find ...)

CodePudding user response:

If you have 2 files: file01.json :

{"a":"1","b":"2"}

file02.json :

{"x":"10","y":"12","z":"15"}

you can:

for f in file*.json ;do cat $f | jq  '.    { creators:[{address: "xxx",share:1}] } '  ; done

result:

{
  "a": "1",
  "b": "2",
  "creators": [
    {
      "address": "xxx",
      "share": 1
    }
  ]
}
{
  "x": "10",
  "y": "12",
  "z": "15",
  "creators": [
    {
      "address": "xxx",
      "share": 1
    }
  ]
}
  • Related