Linux命令jq

是什么

jq 是一个轻量级的json处理命令。可以对json数据进行分片、过滤、映射和转换

jq . 对json数据进行格式化输出

cat ./json.txt
[{"name": "zhangsan","age": 21,"courses": ["语文", "数学", "英语"]},{"name": "lisi","age": 22,"courses": ["物理", "化学", "生物"]}]
cat ./json.txt | jq .
[
  {
    "name": "zhangsan",
    "age": 21,
    "courses": [
      "语文",
      "数学",
      "英语"
    ]
  },
  {
    "name": "lisi",
    "age": 22,
    "courses": [
      "物理",
      "化学",
      "生物"
    ]
  }
]

json中的某个字段

# 取json中第一个分片 中的name
cat ./json.txt | jq '.[0].name'
"zhangsan"
# 取courses 中第一个下标的课程
cat ./json.txt | jq '.[].courses[0]'
"语文"
"物理"

json重新进行整理

# 只输出name 和 age
cat ./json.txt | jq '[.[] | {name:.name, age:.age}]'
[
  {
    "name": "zhangsan",
    "age": 21
  },
  {
    "name": "lisi",
    "age": 22
  }
]
# 输出name和第一个course
cat ./json.txt | jq '[.[] | {name:.name, course:.courses[0]}]'
[
  {
    "name": "zhangsan",
    "course": "语文"
  },
  {
    "name": "lisi",
    "course": "物理"
  }
]

你可能感兴趣的:(Linux命令jq)