jq 引用索引/键及其内部值

问题描述 投票:0回答:1

我有一个类似于以下内容的 JSON:

文件:my_data.json

{
  "hosts": {
    "1.2.3.4": { "name": "name4", "env": "test", "options": "" },
    "1.2.3.5": { "name": "name5", "env": "prod", "options": "opt1,opt2" },
    "1.2.3.6": { "name": "name6", "env": "qa", "options": "" },
    "1.2.3.7": { "name": "name7", "env": "staging", "options": "opt3,opt4" },
    "1.2.3.8": { "name": "name8", "env": "dev", "options": "opt5" },
    "1.2.3.9": { "name": "name9", "env": "prod", "options": "opt6,opt7" }
  }
}

我想从中提取一个 CSV 文件,我尝试了通过谷歌搜索找到的几个选项,但都不起作用。我的目标是得到类似以下的东西:

"1.2.3.4","name4","test",""
"1.2.3.5","name5","prod","opt1,opt2"
"1.2.3.6","name6","dev",""
"1.2.3.7","name7","staging","opt3,opt4"
"1.2.3.8","name8","dev","opt5"
"1.2.3.9","name9","prod","opt6,opt7"

我得到了以下信息,但我无法找到密钥,也没有找到获取它的方法。

jq --raw-output '.hosts[] | [.name, .env, .options] | @csv' my_data.json

这是我的结果,但看起来并不完整。如何为每个对象添加密钥?

"name4","test",""
"name5","prod","opt1,opt2"
"name6","qa",""
"name7","staging","opt3,opt4"
"name8","dev","opt5"
"name9","prod","opt6,opt7"

我做了这个:

jq --raw-output '.hosts | keys_unsorted[] | [.] | @csv' my_data.json

但是那只是获取了键,我还没有找到使用键来寻址对象的方法。

"1.2.3.4"
"1.2.3.5"
"1.2.3.6"
"1.2.3.7"
"1.2.3.8"
"1.2.3.9"

我可以尝试连接两个表,但这可能会导致错误,我知道应该有一种方法可以在 jq 中做到这一点,我只是找不到方法。

我做了几次谷歌搜索,我得到了一个有希望的结果,但它不起作用:

jq --raw-output '.hosts | keys_unsorted[] as $k | [$k, \(.[$k] | .name), \(.[$k] | .env), \(.[$k] | .options)] | @csv' my_data.json

这个返回编译错误:

jq: error: syntax error, unexpected INVALID_CHARACTER (Unix shell quoting issues?) at <top-level>, line 1:
.hosts | keys_unsorted[] as $k | [$k, \(.[$k] | .name), \(.[$k] | .env), \(.[$k] | .options)] | @csv
jq: error: syntax error, unexpected ')', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
.hosts | keys_unsorted[] as $k | [$k, \(.[$k] | .name), \(.[$k] | .env), \(.[$k] | .options)] | @csv
jq: 2 compile errors
json linux ubuntu jq
1个回答
0
投票

使用

to_entries
访问按键:

.hosts | to_entries[] | [.key, (.value | .name, .env, .options)] | @csv
"1.2.3.4","name4","test",""
"1.2.3.5","name5","prod","opt1,opt2"
"1.2.3.6","name6","qa",""
"1.2.3.7","name7","staging","opt3,opt4"
"1.2.3.8","name8","dev","opt5"
"1.2.3.9","name9","prod","opt6,opt7"

演示

© www.soinside.com 2019 - 2024. All rights reserved.