命令行中处理json数据

一、安装

百度brew install、apt install、yum install等

二、常用操作

1.格式化json

XX命令  | jq    #比如cat a.json |jq
XX命令 | jq ''  #比如cat a.json | jq ''

cat a.json | jq '' | less    #如果 json 很长,则可以使用管道传给 less 命令 

2.取指定字段的值

直接输入字段,使用.嵌套访问,例如要获取昨天的信息

curl -s http://t.weather.sojson.com/api/weather/city/101310215 | jq .data.yesterday
响应如下: { "date": "24", "high": "高温 29℃", "low": "低温 23℃", "ymd": "2019-10-24", "week": "星期四", "sunrise": "06:34", "sunset": "18:10", "aqi": 27, "fx": "无持续风向", "fl": "<3级", "type": "多云", "notice": "阴晴之间,谨防紫外线侵扰" }

3.过滤指定字段

使用一个json指定所有字段,如{date, high},获取昨天的最高温度如下

 curl -s http://t.weather.sojson.com/api/weather/city/101310215 | jq .data.yesterday|jq "{date,high}"
响应如下:
{
  "date": "24",
  "high": "高温 29℃"
}

4.获取多个字段的值

使用逗号获取多个

curl -s http://t.weather.sojson.com/api/weather/city/101310215 | jq .data.yesterday|jq ".date, .high"
响应如下: "24" "高温 29℃"

5.筛选数组

直接指定数组的索引即可

curl -s http://t.weather.sojson.com/api/weather/city/101310215 |jq ".data.forecast"|jq ".[0,9]"
响应如下:
{
  "date": "25",
  "high": "高温 29℃",
  "low": "低温 23℃",
  "ymd": "2019-10-25",
  "week": "星期五",
  "sunrise": "06:35",
  "sunset": "18:10",
  "aqi": 44,
  "fx": "无持续风向",
  "fl": "<3级",
  "type": "中雨",
  "notice": "记得随身携带雨伞哦"
}
{
  "date": "03",
  "high": "高温 26℃",
  "low": "低温 24℃",
  "ymd": "2019-11-03",
  "week": "星期日",
  "sunrise": "06:38",
  "sunset": "18:05",
  "fx": "东风",
  "fl": "3-4级",
  "type": "小雨",
  "notice": "雨虽小,注意保暖别感冒"
}
原文地址:https://www.cnblogs.com/feifei-cyj/p/12253847.html