how can I add and remove a new key (i.e "key4": "value4") by bash script?
Please use a dedicated JSON parser, like xidel.
Add a new attribute:
$ xidel -s "input.json" -e '($json).key4:="value4"' # Xidel exclusive syntax, dot notation)
$ xidel -s "input.json" -e '$json("key4"):="value4"' # Xidel exclusive syntax, JSONiq notation)
$ xidel -s "input.json" -e '$json?key4:="value4"' # Xidel exclusive syntax, XPath 3.1 syntax)
$ xidel -s "input.json" -e '{|$json,{"key4":"value4"}|}' # JSONiq syntax (deprecated)
$ xidel -s "input.json" -e 'map:put($json,"key4",4)' # XQuery 3.1 map functions
$ xidel -s "input.json" -e 'map:merge(($json,{"key4":4}))' # XQuery 3.1 map functions
{
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4"
}
Remove the attribute "key3":
$ xidel -s "input.json" --xmlns:jnlib="http://jsoniq.org/function-library" -e 'jnlib:remove-keys($json,"key3")' # JSONiq jnlib functions (deprecated)
$ xidel -s "input.json" -e 'map:remove($json,"key3")' # XQuery 3.1 map functions
{
"key1": "value1",
"key2": "value2"
}
Change the attribute "key3" value to "value4":
$ xidel -s "input.json" -e '($json).key3:="value4"' # Xidel exclusive syntax, dot notation)
$ xidel -s "input.json" -e '$json("key3"):="value4"' # Xidel exclusive syntax, JSONiq notation)
$ xidel -s "input.json" -e '$json?key3:="value4"' # Xidel exclusive syntax, XPath 3.1 syntax)
$ xidel -s "input.json" -e 'map:put($json,"key3","value4")' # XQuery 3.1 map functions
$ xidel -s "input.json" -e 'map:merge(($json,{"key3":"value4"}),{"duplicates":"use-last"})' # XQuery 3.1 map functions
{
"key1": "value1",
"key2": "value2",
"key3": "value4"
}