[英]Extract data from nested JSON and convert to TSV
我正在查看解析嵌套的 json。 对于下面的示例,我知道它出现在 Github 上 - 但是由于敏感性,我无法在此处发布我的实际数据。
我一直在查看jq
的格式,并且可以将每个组件拉出,但不能将它们合并在一起,如下所示。
由于软件限制,我不能使用第 3 方代码。
输入:
{ "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"} ] } ] }
output:
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
,然后使用 append 名称。 例如:
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.