[英]how to use jq to flatten nested keys in the json
I am currently trying to process below json using jq commandline我目前正在尝试使用 jq 命令行在 json 下进行处理
cat api-docs.json | jq '.paths'
{
...
...
"paths": {
"/pets": {
"get": {
...
...
"post": {
...
...
"/pets/{petId}": {
"get": {
...
https://jqplay.org/s/GV2zMjbCWK https://jqplay.org/s/GV2zMjbCWK
I need a flattened info from swagger spec above我需要来自上面 swagger 规范的扁平化信息
[ "GET /pets", "POST /pets", "GET /pets/{petId}" ]
is this even possible with jq
command ?这甚至可以使用
jq
命令吗?
with below I get each value independently下面我独立地得到每个值
.paths|{k:keys,v:map(keys)}
But what I need is a way to combine keys at nested level to get above result ie array of "METHOD /PATH"但我需要的是一种在嵌套级别组合键以获得高于结果的方法,即“方法/路径”数组
The following filter produces the results you want, as shown below:以下过滤器产生您想要的结果,如下所示:
.paths
| to_entries
| map( .key as $path
| ( .value | to_entries[]
| if .key == "get" then "GET"
elif .key == "post" then "POST"
else empty end ) as $verb
| $verb + " " + $path )
Output:输出:
[
"GET /pets",
"POST /pets",
"GET /pets/{petId}"
]
You may want to include more "verbs", or handle the verbs programmatically, eg您可能希望包含更多“动词”,或以编程方式处理动词,例如
.paths
| to_entries
| map(( .value | to_entries[] | .key | ascii_upcase ) + " " + .key)
The key to the solution here is to_entries
, which produces an array of objects of the form {"key": _, "value": _ }.此处解决方案的关键是
to_entries
,它生成 {"key": _, "value": _ } 形式的对象数组。 Apart from map
, which here saves having to unpack the array and then repack it, the rest is syntax :-)除了
map
,这里省去了解包数组然后重新打包它,剩下的就是语法:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.