Search code examples
jsonshelljqkeyvaluepair

Dynamically add key value pair in jSON object using shell


I have a json object named version6json as follows

{
  "20007.098": {
    "os_version": "6.9",
    "kernel": "2.6.32-696",
    "sfdc-release": "2017.08"
  },
  "200907.09678”: {
    "os_version": "6.9",
    "kernel": "2.6.32-696",
    "sfdc-release": "201.7909"
  },
  "206727.1078”: {
    "os_version": "6.9",
    "kernel": "2.6.32-696.10.2.el6.x86_64",
    "sfdc-release": "20097.109”
  }
}

I want to add one more key value pair. The key is also a variable and the value too. bundle_release="2019.78" and value= {"release":"2018.1006","kernel":"2.6.32-754.3.5.el6.x86_64","os":"6.10","current":true} Now I want the bundle_release as key and value as its value, So the new entry would be "2018.1006": {"release":"2018.1006","kernel":"2.6.32-754.3.5.el6.x86_64","os":"6.10","current":true}

To achieve this, I am doing the folllowing

echo "$version6json" | jq --arg "$bundle_release" "$value" '. + {$bundle_release: "${value}"}'

Any help will be appriciated.

P.S- The question is edited as suggested by peak


Solution

  • First, when specifying a key name using a variable in the way you are doing, the variable must be parenthesized, so you would have:

     {($bundle_release): ...}
    

    Next, jq variables are not the same as shell variables and should be specified without quoting them, and without using bash-isms.

    Third, when setting the value of the shell variable named value, you would have to quote the expression appropriately.

    Fourth, to simplify things, use --argjson for $value.

    Fifth, your sample JSON is not quite right. Once it's fixed, the following will work in a bash or bash-like environment (assuming you're using a version of jq that supports --argjson):

    bundle_release="1034,567"
    value='{"release":"2018.1006","kernel":"2.6.32-754.3.5.el6.x86_64","os":"6.10","current":true}'
    
    jq --arg b "$bundle_release" --argjson v "$value"  '
      . + {($b): $v}' <<< "$version6json"