change json file by bash script

前端 未结 5 1096
醉话见心
醉话见心 2020-12-12 12:20

I need your help to solve the following problem: I have a JSON file that looks like this:

{
  \"key1\": \"value1\",
  \"key2\": \"value2\",
  \"key3\": \"val         


        
5条回答
  •  -上瘾入骨i
    2020-12-12 12:40

    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:

    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
    }
    

    Remove the attribute-value pair "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
    }
    

提交回复
热议问题