[英]Extract data from nested JSON and convert to TSV
I'm looking at parsing nested json.我正在查看解析嵌套的 json。 For the example below, I know that it appears on Github - however due to sensitivity I cannot post my actual data on here.对于下面的示例,我知道它出现在 Github 上 - 但是由于敏感性,我无法在此处发布我的实际数据。
I've Been looking at jq
for formatting, and can pull each component out, but cannot merge them together such that it looks like the below.我一直在查看jq
的格式,并且可以将每个组件拉出,但不能将它们合并在一起,如下所示。
BEcuase of software restrictions, I cannot use 3rd party code.由于软件限制,我不能使用第 3 方代码。
input:输入:
{ "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: 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
EDIT: Current code is such that I loop through all the instances of instances
using and then append the names.编辑:当前代码是这样的,我循环使用所有实例instances
,然后使用 append 名称。 For example:例如:
cat sampleData.json | jq -c '.' | while read i; do
echo $i, & jq '.instances' sampleData.json
done
A slight shorter (though marginally more complex) version of @anubhava's answer: @anubhava 的回答稍微短一些(虽然稍微复杂一点):
jq -r '.asgs[] | .name as $n | (.instances[] | [$n, .id, .az, .state] | @tsv)' file.json
This "remembers" each name before producing a tab-separated line for each instance, inserting the correct name in each row.这会在为每个实例生成制表符分隔的行之前“记住”每个名称,并在每一行中插入正确的名称。
You may use this jq
:你可以使用这个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
You can use a generic map
to create an extra entry per-instance:您可以使用通用map
为每个实例创建一个额外的条目:
jq -r '.asgs[] | [.name] + (.instances[] | map(.)) | @tsv'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.