其他分享
首页 > 其他分享> > jq命令

jq命令

作者:互联网

1. 查询

2. 修改

有json

{
  "honesty": "Apple Jack",
  "laughter": "Pinkie Pie",
  "loyalty": "Rainbow Dash"
}
cat 1.json | jq to_entries
[
  {
    "key": "honesty",
    "value": "Apple Jack"
  },
  {
    "key": "laughter",
    "value": "Pinkie Pie"
  },
  {
    "key": "loyalty",
    "value": "Rainbow Dash"
  }
]
cat 1.json | jq to_entries | jq from_entries
{
  "honesty": "Apple Jack",
  "laughter": "Pinkie Pie",
  "loyalty": "Rainbow Dash"
}
#!/bin/bash

m_key="honesty"
m_value="aaa"

cat ./1.json |
  jq "to_entries |
       map(if .key == \"${m_key}\"
          then . + {\"value\":\"${m_value}\"}
          else .
          end
         ) |
      from_entries"

./1.sh
{
  "honesty": "aaa",
  "laughter": "Pinkie Pie",
  "loyalty": "Rainbow Dash"
}

封装成函数

# set obj's value
# json_set_value <json> <key for index > <new value of value>
function json_set_value()
{
    local json="$1"
    local m_key="$2"
    local m_value="$3"

    echo $json |
    jq " to_entries |
      map(if .key == \"${m_key}\"
          then . + {\"value\":\"${m_value}\"}
          else .
          end
         ) |
      from_entries"
}
# set obj's key
# json_set_key <json> <key for index> <new value of key>
function json_set_key()
{
    local json="$1"
    local m_key="$2"
    local m_new_key="$3"

    echo $json |
    jq " to_entries |
      map(if .key == \"${m_key}\"
          then . + {\"key\":\"${m_new_key}\"}
          else .
          end
         ) |
      from_entries"
}

function test1()
{
    str=$(json_set_value "$(cat ./1.json)" "honesty" "bbb")
    echo "$str"
    str=$(json_set_key "$(cat ./1.json)" "honesty" "bbb")
    echo "$str"
}

标签:set,honesty,jq,value,命令,json,key,entries
来源: https://www.cnblogs.com/yangxinrui/p/16314070.html