Json
如何列印 JSON 文件的路徑和鍵值
我想逐行列印包含鍵值的json文件的每個路徑和值。給定以下json和jq,是否也可以為每一行添加值?如果不使用jq還有其他方法嗎?我正在考慮類似於snmpwalk for json的東西。另外,我想做的事情有技術術語嗎?
$ cat short.json | jq '.' { "Reservations": [ { "Groups": [], "Instances": [ { "ImageId": "ami-a", "InstanceId": "i-a", "InstanceType": "t2.micro", "KeyName": "ubuntu" } ] } ] } $ cat short.json | jq -r '[paths | map(.|tostring) | join(".")]' [ "Reservations", "Reservations.0", "Reservations.0.Groups", "Reservations.0.Instances", "Reservations.0.Instances.0", "Reservations.0.Instances.0.ImageId", "Reservations.0.Instances.0.InstanceId", "Reservations.0.Instances.0.InstanceType", "Reservations.0.Instances.0.KeyName" ]
多行輸出中的單行範例:
"Reservations.0.Instances.0.ImageId": "ami-a",
如果可以使用複制和粘貼 將輸出格式化為在jq中使用,則可以使用 linux cut 輕鬆分離值:
'.Reservations[].Instances[].ImageId': "ami-a"
$ cat short.json | jq -r '.Reservations[].Instances[].ImageId' ami-a
我不是很了解,
jq
但我在網際網路上發現了這個,我認為它適用於你的情況:剪切和粘貼版本:
jq -r 'paths(scalars) as $p | [ ( [ $p[] | tostring ] | join(".") ), ( getpath($p) | tojson )] | join(": ")' short.json
易於閱讀的版本:
jq -r ' paths(scalars) as $p | [ ( [ $p[] | tostring ] | join(".") ) , ( getpath($p) | tojson ) ] | join(": ") ' short.json
結果:
Reservations.0.Instances.0.ImageId: "ami-a" Reservations.0.Instances.0.InstanceId: "i-a" Reservations.0.Instances.0.InstanceType: "t2.micro" Reservations.0.Instances.0.KeyName: "ubuntu"
而且因為我想要獎勵積分,所以
sed
你可以使用以下技巧來獲得你想要的輸出:... | sed "s/^/\'./; s/:/\':/; s/\.0/[]/g"
哪個輸出:
'.Reservations[].Instances[].ImageId': "ami-a" '.Reservations[].Instances[].InstanceId': "i-a" '.Reservations[].Instances[].InstanceType': "t2.micro" '.Reservations[].Instances[].KeyName': "ubuntu"