jq使用

取出指定字段

例如对于

1
2
3
4
{
  "abc": "123",
  "def": [{ "111": "..." }, { "222": "..." }]
}

可以通过 jq '.def[0]' test.json 取出数组第一个元素:

1
# 输出: {"111":"..."}

常用取值方式:

1
2
3
4
5
6
7
8
9
10
11
# 取出单个字段
jq '.abc' test.json           # "123"

# 取出嵌套字段
jq '.def[0]."111"' test.json  # "..."

# 取出数组所有元素
jq '.def[]' test.json

# -c 参数压缩输出(单行)
jq -c '.def[0]' test.json > output.json

把当前内容放到一个结构体里构成一个新的json

假如我们已经有了一个:

1
2
3
4
[
  { "role": "system", "content": "有用的助手" },
  { "role": "user", "content": "用户: halo" }
]

希望把上面的内容包装到下面的messages:

1
2
3
4
5
6
{
  "model": "...",
  "messages": [...],
  "temperature": 0,
  "max_tokens": 4096
}

可以:

1
2
3
4
5
6
jq '{
  model: "local-model",
  messages: .,
  temperature: 0,
  "max_tokens": 4096
}' input.json > payload.json

生成的payload.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
  "model": "local-model",
  "messages": [
    {
      "role": "system",
      "content": "有用的助手"
    },
    {
      "role": "user",
      "content": "用户: halo"
    }
  ],
  "temperature": 0,
  "max_tokens": 4096
}

然后就可以通过:

1
2
3
curl -X POST http://localhost:8000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d @payload.json

进行请求了

过滤和筛选

根据条件筛选数组元素:

1
2
3
4
5
6
7
8
# 筛选满足条件的元素
jq '.[] | select(.id > 10)' data.json

# 筛选字符串匹配
jq '.[] | select(.name | contains("test"))' data.json

# 多条件筛选
jq '.[] | select(.age >= 18 and .status == "active")' data.json

数组和对象操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# 获取数组长度
jq '.def | length' test.json

# 获取对象的 keys
jq 'keys' test.json

# 添加新字段
jq '. + {"new_field": "value"}' test.json

# 删除字段
jq 'del(.abc)' test.json

# 数组切片(前3个)
jq '.def[0:3]' test.json

# 数组映射(对每个元素操作)
jq '.def | map(.id)' test.json

# 数组求和
jq '[.def[].id] | add' test.json

管道操作

1
2
3
4
5
6
7
8
# 链式操作
jq '.def[] | select(.id > 10) | .name' test.json

# 重组数据结构
jq '{id: .id, name: .name | ascii_upcase}' test.json

# 统计信息
jq '{count: length, sum: map(.value) | add}' items.json

实用技巧

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 格式化美化 JSON
jq '.' input.json

# 从 API 响应中提取字段
curl -s api.example.com/data | jq '.results[0].id'

# 合并多个 JSON 文件
jq -s '.' file1.json file2.json > merged.json

# 读取并修改配置
jq '.timeout = 30' config.json > config.tmp && mv config.tmp config.json

# 处理 null 值
jq 'if .value then .value else "default" end' data.json