簡體   English   中英

從嵌套的 JSON 中提取數據並轉換為 TSV

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM