shell 使用jq解析json字符串数组

echo json.txt | jq '.' 输出整个json字符串

echo json.txt | jq '.[0]' 取出数组中第一个object

echo json.txt | jq '.[0].name' 取出数组第一个object中键为name的值

root@JDBox_LuBan:~# cat json.txt | jq '.[0].name' 
"Google"

json.txt:

[
  {
    "name": "Google",
    "location": {
      "street": "1600 Amphitheatre Parkway",
      "city": "Mountain View",
      "state": "California",
      "country": "US"
    },
    "employees": [
      {
        "name": "Michael",
        "division": "Engineering"
      },
      {
        "name": "Laura",
        "division": "HR"
      },
      {
        "name": "Elise",
        "division": "Marketing"
      }
    ]
  }
]

1.嵌套解析:

# cat json.txt | jq '.[0].location.city'
"Mountain View"

2.获取JSON中的所有键:

# cat json.txt | jq '.[0]|keys'
[
  "employees",
  "location",
  "name"
]

 3.获取键值对的个数,或者数组长度:

cat json.txt | jq '.[0].employees|length'
3
# 取键foo的值:
echo '{"foo": 42, "bar": "less interesting data"}' | jq '.foo'
42
# 获取json所有键:
echo '{"foo": 42, "bar": "less interesting data"}' | jq 'keys'
[
"bar",
"foo"
]
# has判断是否存在某个key
echo '{"foo": 42, "bar": "less interesting data"}' | jq 'has("foo")' 
true
# 获取键值对的个数,或者数组长度
echo '{"foo": 42, "bar": "less interesting data"}' | jq 'length' 
2

参考:https://blog.csdn.net/yanbingquan/article/details/50770911

posted @ 2022-11-28 14:57  船长博客  阅读(4317)  评论(0编辑  收藏  举报
永远相信美好的事情即将发生!