简体   繁体   中英

jq update contents of one file to another as key value

I am trying to update branches.json.branch2 values from branch2.json.Employes values Using jq, How can I merge content of one file to another file Below are the files

I have tried this but it did work, it just prints the original data without updating the details

#!/bin/sh
#call file with branch name for example ./update.sh branch2
set -xe
branchName=$1
fullPath=`pwd`/$1".json"
list=$(cat ${fullPath})
branchDetails=$(echo ${list} | /usr/local/bin/jq -r '.Employes')
newJson=$(cat branches.json | 
      jq --arg updateKey "$1" --arg updateValue "$branchDetails" 'to_entries | 
       map(if .key == "$updateKey"
          then . + {"value":"$updateValue"} 
          else . 
          end) | 
          from_entries')

echo $newJson &> results.json

branch1.json

{
  "Employes": [
    {
      "Name": "Ikon",
      "age": "30"
    },
    {
      "Name": "Lenon",
      "age": "35"
    }
  ]
}

branch2.json

{
  "Employes": [
    {
      "Name": "Ken",
      "age": "40"
    },
    {
      "Name": "Frank",
      "age": "23"
    }
  ]
}

brances.json / results.json fromat

{
  "branch1": [
      {
        "Name": "Ikon",
        "age": "30"
      },
      {
        "Name": "Lenon",
        "age": "35"
      }
    ],
  "branch2": [
      {
        "Name": "Ken",
        "age": "40"
      },
      {
        "Name": "Frank",
        "age": "23"
      }
    ]

}

Note: I dont have the list of all the branch files at any given point, so script is responsible only to update the that branch details.

If the file name is the name of the property you want to update, you could utilize input_filename to select the files. No testing needed, just pass in the files you want to update. Just be aware of the order you pass in the input files.

Merge the contents of the file as you see fit. To simply replace, just do a plain assignment.

$ jq 'reduce inputs as $i (.;
    .[input_filename|rtrimstr(".json")] = $i.Employes
)' branches.json branch{1,2}.json

Your script would just need to be:

#!/bin/sh
#call file with branch name for example ./update.sh branch2
set -xe
branchName=$1
newJson=$(jq 'reduce inputs as $i (.; .[input_filename|rtrimstr(".json")] = $i.Employees)' branches.json "$branchName.json")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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