我正在解析嵌套的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'