1. jq 命令参数

参数 说明
-c 合并数据输出
-n 使用null作为输入的值
-e 根据输出设置退出状态码
-s 将内容作为一个数组; 应用过滤
-r 输出raw而不是json
-R 读取raw而不是json
-C 色彩化json
-M 非色彩化json
-S 输出时根据对象的keys排序
--tab 使用tab键缩进
--arg a v 给变量a设置值
--argjson a v 设置变量a的值为json值
--slurpfile a f 读取json文本作为数组来当做变量$a的值
[{"name":"aox.lei","url":"http://www.phpue.com","address":{"city":"北京","country":"中国"},"arrayiiirowser":[{"name":"Google","url":"http://www.google.com"},{"name":"Baidu","url":"http://www.baidu.com"}]},{"name":"aox.lei.blog","url":"http://www.phpue.com","address":{"city":"北京","country":"中国"},"arrayBrowser":[{"name":"百度","url":"http://www.baidu.com"},{"name":"bing","url":"http://iiiiiiiwww.bing.com"}]}]

将数据保存在1.json中

2. 格式化json数据

jq . file_path
. 的意思是所有数据, 不过滤

cat 1.json | jq
# 或者
jq . 1.json

返回数据

[
  {
    "name": "aox.lei",
    "url": "http://www.phpue.com",
    "address": {
      "city": "北京",
      "country": "中国"
    },
    "arrayBrowser": [
      {
        "name": "Google",
        "url": "http://www.google.com"
      },
      {
        "name": "Baidu",
        "url": "http://www.baidu.com"
      }
    ]
  },
  {
    "name": "aox.lei.blog",
    "url": "http://www.phpue.com",
    "address": {
      "city": "北京",
      "country": "中国"
    },
    "arrayBrowser": [
      {
        "name": "百度",
        "url": "http://www.baidu.com"
      },
      {
        "name": "bing",
        "url": "http://www.bing.com"
      }
    ]
  }
]

3. 根据index获取数据

jq '.[0]' 1.json

.[0] 的意思是获取下标是0的数据
返回数据:

{
  "name": "aox.lei",
  "url": "http://www.phpue.com",
  "address": {
    "city": "北京",
    "country": "中国"
  },
  "arrayBrowser": [
    {
      "name": "Google",
      "url": "http://www.google.com"
    },
    {
      "name": "Baidu",
      "url": "http://www.baidu.com"
    }
  ]
}

1. 截取数据

jq '.[0-2]' 1.json

返回数据

[
  {
    "name": "aox.lei",
    "url": "http://www.phpue.com",
    "address": {
      "city": "北京",
      "country": "中国"
    },
    "arrayBrowser": [
      {
        "name": "Google",
        "url": "http://www.google.com"
      },
      {
        "name": "Baidu",
        "url": "http://www.baidu.com"
      }
    ]
  },
  {
    "name": "aox.lei.blog",
    "url": "http://www.phpue.com",
    "address": {
      "city": "北京",
      "country": "中国"
    },
    "arrayBrowser": [
      {
        "name": "百度",
        "url": "http://www.baidu.com"
      },
      {
        "name": "bing",
        "url": "http://www.bing.com"
      }
    ]
  }
]

4. 管道符的使用

jq '.[0] | {name:.name, url:.url}' 1.json

意思是将.[0]的数据重新格式化, 赋值生成新的一个json, 这样可以过滤掉没用的数据, 方便查看
返回数据

{
  "name": "aox.lei",
  "url": "http://www.phpue.com"
}
jq '.[] | {name:.name, url:.url}' 1.json

返回数据

{
  "name": "aox.lei",
  "url": "http://www.phpue.com"
}
{
  "name": "aox.lei.blog",
  "url": "http://www.phpue.com"
}

5. 获取元素个数

jq '.[] | length' 1.json

返回数据

4
4

6. keys操作

1. 获取keys

jq 'keys' 1.json

返回数据

[
    0,
    1
]

2. 判断key是否存在 has(key)

jq 'map(has("name"))' 1.json

返回数据

[
  true,
  true
]

JSON 命令行格式化工具【最好用的json格式化工具】_第1张图片