从嵌套的JSON中提取数据并转换为TSV



我正在研究解析嵌套的json。对于下面的例子,我知道它出现在Github上,但由于敏感性,我无法在这里发布我的实际数据。

我一直在查看jq的格式,可以提取每个组件,但不能将它们合并在一起,使其看起来像下面这样。

由于软件限制,我不能使用第三方代码。

输入:

{   "asgs": [
{
"name": "test1",
"instances": [
{"id": "i-9fb75dc", "az": "us-east-1a", "state": "InService"},
{"id": "i-95393ba", "az": "us-east-1a", "state": "Terminating:Wait"},
{"id": "i-241fd0b", "az": "us-east-1b", "state": "InService"}
]
},
{
"name": "test2",
"instances": [
{"id": "i-4bbab16", "az": "us-east-1a", "state": "InService"},
{"id": "i-417c312", "az": "us-east-1b", "state": "InService"}
]
}   ] }

输出:

test1   i-9fb75dc       us-east-1a      InService
test1   i-95393ba       us-east-1a      Terminating:Wait
test1   i-241fd0b       us-east-1b      InService
test2   i-4bbab16       us-east-1a      InService
test2   i-417c312       us-east-1b      InService

编辑:当前的代码是这样的,我循环使用instances的所有实例,然后附加名称。例如:

cat sampleData.json | jq -c '.' | while read i; do
echo $i, & jq '.instances' sampleData.json
done

@anubhava答案的一个稍短(尽管稍微复杂(的版本:

jq -r '.asgs[] | .name as $n | (.instances[] | [$n, .id, .az, .state] | @tsv)' file.json

这将"记住"每个名称,然后为每个实例生成一个以制表符分隔的行,在每行中插入正确的名称。

您可以使用此jq:

jq -r '.asgs[] | .name + "t" + (.instances[] | .id + "t" + .az + "t" + .state)' file.json

test1   i-9fb75dc   us-east-1a  InService
test1   i-95393ba   us-east-1a  Terminating:Wait
test1   i-241fd0b   us-east-1b  InService
test2   i-4bbab16   us-east-1a  InService
test2   i-417c312   us-east-1b  InService

您可以使用通用map为每个实例创建一个额外的条目:

jq -r '.asgs[] | [.name] + (.instances[] | map(.)) | @tsv'