Open aibangjuxin opened 6 months ago
jq
是一个轻量级且强大的命令行JSON处理器,它允许你通过编写类似于域名的查询语法来处理JSON数据。以下是一些使用 jq
进行高级过滤的示例:
选择特定字段:
jq '.fieldName'
选择所有字段:
jq '.'
选择多个特定字段:
jq '.fieldName1, .fieldName2'
过滤数组中的对象:
jq '.arrayField[] | select(.fieldName == "value")'
使用正则表达式过滤字段值:
jq --arg regex '.*your_regex.*' '.arrayField[] | select(.fieldName | test($regex))'
获取数组中第一个元素:
jq '.arrayField[0]'
获取数组中最后一个元素:
jq '.arrayField[-1]'
计算数组中元素的数量:
jq '.arrayField | length'
计算数组中满足条件的元素数量:
jq '.arrayField | length | select(. > 0)'
对数组中的元素进行排序:
jq '.arrayField | sort_by(.fieldName)'
对数组中的元素进行逆序:
jq '.arrayField | reverse'
从嵌套的JSON结构中提取信息:
jq '.parentField[].childField'
使用条件表达式:
jq '.arrayField[] | if .fieldName == "value" then . else empty end'
创建新的JSON结构:
jq '[ .arrayField[] | {newField: .fieldName} ]'
合并多个JSON文件:
jq -s '.[]' file1.json file2.json > merged.json
递归查询所有匹配的字段:
jq 'recurse(.[]; .fieldName?)'
使用变量:
jq --arg name "value" '. | select(.fieldName == $name)'
格式化JSON输出:
jq '.'
计算字段的总和:
jq '.arrayField | add'
将JSON对象转换为键值对数组:
jq 'to_entries | .[] | .key as $k | .value as $v | "\($k): \($v)"'
这些示例展示了 jq
的一些强大功能,但 jq
的能力远不止这些。根据你的具体需求,你可以编写更复杂的查询来处理JSON数据。记得在使用 jq
之前,你需要安装它。在大多数Linux发行版中,你可以使用包管理器来安装。
Here are some examples of more advanced usage of
jq
:Recursive Descent
Suppose you have a JSON file
data.json
containing a nested object:You can use
jq
to recursively traverse the object and extract specific values:This will output:
The
..
syntax tellsjq
to recursively traverse the object, and the.name?
syntax extracts the value of thename
property if it exists.Aggregating Data
Suppose you have a JSON file
data.json
containing an array of objects:You can use
jq
to calculate the average age:This will output:
The
add
function sums up the values, and thelength
function returns the length of the array. The/
operator performs division.Grouping and Sorting
Suppose you have a JSON file
data.json
containing an array of objects:You can use
jq
to group the data by department and calculate the total salary for each department:This will output:
The
group_by
function groups the data by department, and themap
function extracts the salaries for each group. Theadd
function sums up the salaries.Merging Data
Suppose you have two JSON files,
data1.json
anddata2.json
, containing arrays of objects:You can use
jq
to merge the two files based on thename
property:This will output:
The
-s
option tellsjq
to read the input files sequentially, and thegroup_by
function merges the data based on thename
property.These are just a few examples of the many advanced things you can do with
jq
. I hope this helps!