how can I add and remove a new key (i.e "key4": "value4"
) by bash script?
Using a dedicated JSON tool, like xidel, would be a better idea than to use pure Bash functions.
Add a new attribute-value pair
xidel -s '{"a":1,"b":2,"c":3}' -e '($json).d:=4' # dot notation
xidel -s '{"a":1,"b":2,"c":3}' -e '{|$json,{"d":4}|}' # JSONiq (deprecated)
xidel -s '{"a":1,"b":2,"c":3}' -e 'map:put($json,"d",4)' # XQuery
xidel -s '{"a":1,"b":2,"c":3}' -e 'map:merge(($json,{"d":4}))' # XQuery
{
"a": 1,
"b": 2,
"c": 3,
"d": 4
}
Remove the attribute-value pair "c":3
xidel -s '{"a":1,"b":2,"c":3}' --xmlns:jnlib="http://jsoniq.org/function-library" -e 'jnlib:remove-keys($json,"c")' # JSONiq (deprecated)
xidel -s '{"a":1,"b":2,"c":3}' -e 'map:remove($json,"c")' # XQuery
{
"a": 1,
"b": 2
}
Change value of "c"
attribute to 4
xidel -s '{"a":1,"b":2,"c":3}' -e '($json).c:=4'
xidel -s '{"a":1,"b":2,"c":3}' -e 'map:put($json,"c",4)'
xidel -s '{"a":1,"b":2,"c":3}' -e 'map:merge(($json,{"c":4}),{"duplicates":"use-last"})'
{
"a": 1,
"b": 2,
"c": 4
}