Bash script to Add a new key value pair dynamically in Json

Viewed 1304

My JSON file is,

{
  "student1": {
    "Name": "Caroline",
    "Age": "24",
    "email": "Caroline123@gmail.com",
    "Phone": "1234567890",
    "Blood group": "O+ve"
  }
}

My desired output is,

{
  "student1": {
    "Name": "Caroline",
    "Age": "24",
    "email": "Caroline123@gmail.com",
    "Phone1": "1234567890",
    "Phone2": "1267345980",
    "Phone3": "9865432130",
    "Blood group": "O+ve"
  }
}

The new key-value pairs Phone1, Phone2 and Phone3 , whose values are stored in the array called VALUES, needs to be added in the place of the key Phone

m=1
for i in ${VALUES[@]}
do
  jq --arg newval "$i" '.student1 += { VALUES$m: $newval }' <<<"$filepath"
  let "m += 1"
done

Above is my code, But it's not working! Can anyone please help me to get the desired output!

1 Answers

You can use += operator such as

jq '.student1 += { "Phone2": "1267345980", "Phone3": "9865432130" }'

and rename existing key Phone to Phone1 by using

jq --sort-keys '.student1 += { "Phone2": "1267345980", "Phone3": "9865432130" }| .[] | .["Phone1"] = .Phone | del(.Phone) | {"Student1" : . }'

Demo

Edit( due to your last edit ): Considering you have an array VALUES such as

$ declare -p VALUES
declare -a VALUES='([0]="\"1267345980\"" [1]="\"9865432130\"")'

and have a JSON file named Students.json, then use

m=2
for i in "${VALUES[@]}" 
do  
  cat <<< $(jq '.student1 += { "Phone'"${m}"'" : '"${i}"'}' Students.json) > Students.json
  let "m += 1"   
done

in order to add the elements with keys Phone2 and Phone3 taken from the array

P.S.: tested on GNU/Linux

Related