mac 下使用shell 命令 jq 解析json

官网
https://stedolan.github.io/jq/download/


安装
brew install jq


创建json文件,file.json
{
    "code": 200,
    "msg": "请求成功",
    "data": {
        "username": "abc",
        "mobile": "18611751121"
    },
    "task":[{
        "username": "abc1",
        "mobile": "18611751121"
    },
    {
        "username": "abc2",
        "mobile": "18611751121"
    }]
}


获取value
(testenv3.7) localhost:testenv3.7 macname$ jq .msg file.json 
"请求成功"
(testenv3.7) localhost:testenv3.7 macname$ 



获取value
(testenv3.7) localhost:testenv3.7 macname$ jq .code file.json 
200
(testenv3.7) localhost:testenv3.7 macname$ 



获取value
(testenv3.7) localhost:testenv3.7 macname$ jq .data file.json 
{
  "username": "abc",
  "mobile": "18611751121"
}
(testenv3.7) localhost:testenv3.7 macname$ 



获取子对象的值
(testenv3.7) localhost:testenv3.7 macname$ jq .data.username file.json 
"abc"
(testenv3.7) localhost:testenv3.7 macname$ 



获取数组子元素的值
(testenv3.7) localhost:testenv3.7 macname$ jq .task[0].username file.json 
"abc1"
(testenv3.7) localhost:testenv3.7 macname$ 

(testenv3.7) localhost:testenv3.7 macname$ jq .task[1].username file.json 
"abc2"
(testenv3.7) localhost:testenv3.7 macname$ 

参考:

https://www.linuxidc.com/Linux/2014-03/98041.htm

原文地址:https://www.cnblogs.com/sea-stream/p/11984010.html