I need your help to solve the following problem: I have a JSON file that looks like this:
{
\"key1\": \"value1\",
\"key2\": \"value2\",
\"key3\": \"val
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.
Dot notation:
echo '{"a":1,"b":2,"c":3}' | xidel -s - -e '($json).d:=4'
{
"d": 4,
"a": 1,
"b": 2,
"c": 3
}
JSONiq:
echo '{"a":1,"b":2,"c":3}' | xidel -s - -e '{|$json,{"d":4}|}'
{
"a": 1,
"b": 2,
"c": 3,
"d": 4
}
XQuery 3.1 (requires Xidel 0.9.9-beta):
echo '{"a":1,"b":2,"c":3}' | xidel -s - -e 'map:put($json,"d",4)'
{
"d": 4,
"a": 1,
"b": 2,
"c": 3
}
echo '{"a":1,"b":2,"c":3}' | xidel -s - -e 'map:merge(($json,{"d":4}))'
{
"a": 1,
"b": 2,
"c": 3,
"d": 4
}
"d":4
:JSONiq:
echo '{"a":1,"b":2,"c":3,"d":4}' | xidel -s - --xmlns:jnlib="http://jsoniq.org/function-library" -e 'jnlib:remove-keys($json,"d")'
{
"a": 1,
"b": 2,
"c": 3
}
XQuery 3.1 (requires Xidel 0.9.9-beta):
echo '{"a":1,"b":2,"c":3,"d":4}' | xidel -s - -e 'map:remove($json,"d")'
{
"a": 1,
"b": 2,
"c": 3
}