简体   繁体   English

如何通过所需的键 jq 在嵌套的 json 中

[英]how to jq by the desired key is inside nested json

Here is the id.json这是 id.json

{
    "name": "peter",
    "path": "desktop/name",
    "description": "male",
    "env1": {
        "school": "AAA",
        "height": "150",
        "weight": "80"
    },
    "env2": {
        "school": "BBB",
        "height": "160",
        "weight": "70"
    }
}

it can be more env3, env4, etc created automatically I am trying to get the env1 by using height and weight as key so the output can look like:它可以是自动创建的更多 env3、env4 等我试图通过使用高度和重量作为键来获取 env1,因此输出看起来像:

env1:height:150
env1:weight:80
env2:height:160
env2:weight:70
env3:height:xxx
.
.
.

My shell command jq .env1.height... id.json tried can only get the output by using env1, env2 as key, but it cannot handle env3, env4.我的shell命令 jq .env1.height... id.json 试过只能通过使用env1,env2作为键来获取输出,但它不能处理env3,env4。 And also, using jq to_entries[] to convert the json defined by key and value, but the first few row made me cannot get .value.weight as output.而且,使用 jq to_entries[] 来转换由 key 和 value 定义的 json,但是前几行让我无法得到 .value.weight 作为输出。 Any idea please?请问有什么想法吗?

Update: edited the json to remove these three line更新:编辑 json 以删除这三行

"name": "peter",
"path": "desktop/name",
"description": "male",

Then run below command:然后运行以下命令:

jq 'to_entries[] | select(.value.height!=null) | [.key, .value.height, .value.weight]' id2.json 

I can get below result我可以得到以下结果

[
  "dev",
  "1",
  "1"
]
[
  "sit",
  "1",
  "1"
]

This is almost what I need, but any idea to remove the outer level json please?这几乎是我所需要的,但是有什么想法可以删除外层 json 吗?

Using your data as initially presented, the following jq program:使用最初提供的数据,以下 jq 程序:

keys_unsorted[] as $k 
| select($k|startswith("env"))
| .[$k] | to_entries[]
| select(.key|IN("height","weight"))
| [$k, .key, .value]
| join(":")

produces生产

env1:height:150
env1:weight:80
env2:height:160
env2:weight:70

An answer to the supplementary question补充问题的答案

According to one interpretation of the supplementary question, a solution would be:根据对补充问题的一种解释,解决方案是:

keys_unsorted[] as $k 
| .[$k]
| objects
| select(.height and .weight)
| to_entries[]
| select(.key|IN("height","weight"))
| [$k, .key, .value]
| join(":")

Equivalently, but without the redundancy:等效地,但没有冗余:

["height","weight"] as $hw
| keys_unsorted[] as $k 
| .[$k]
| objects 
| . as $object
| select(all($hw[]; $object[.]))
| $hw[]
| [$k, ., $object[.]]
| join(":")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM