
如何在 shell 上解析 JSON 輸出?
例如,Amazon Web Services 提供 CLI 來擷取實例的狀態:
$ aws ec2 describe-instances <my_instance_id>
但該命令傳回一個 JSON 字串。該命令的輸出如下所示:
$ aws ec2 describe-instances x12345
{
"Reservations" :
{
"OwnerId": "1345345"
"Groups": [],
"SecurityGroups": [
{
"Foo" : "yes"
"Bar" : "no
}
]
}
}
是否有可用於解析 JSON 輸出的內建 shell?
例如,我想在 shell 變數中捕獲FOO
以下內容output["Reservations"]["SecurityGroups"][0]{"Foo"}
。
如果有幫助的話,我對可以在 Zsh 上運行的解決方案特別感興趣。
答案1
據我了解,您正在尋找“Foo”的值。這是真的使用 shell 命令列工具很容易做到jq
。sed
就像它實作了自己的解析器語言。鑑於你的例子:
json='
{
"Reservations" :
{
"OwnerId" : "1345345",
"Groups" : [],
"SecurityGroups" : [
{
"Foo" : "yes",
"Bar" : "no"
}
]
}
}'
jq
可以yes
簡單得到:
printf %s "$json" |
jq '.[].SecurityGroups[0].Foo?'
輸出
"yes"
您可以使用.dot
符號遍歷物件雜湊或字典列表,並且可以使用數字方括號索引更簡單地對索引數組進行索引,正如您可能已經猜到的那樣。在上面的命令中,我使用空索引形式來指示我希望擴展該層級的所有可迭代項目。這樣理解可能比較容易理解:
printf %s "$json" | jq '.[][]'
……這會分解散列中第二級項目的所有值並讓我...
"1345345"
[]
[
{
"Foo": "yes",
"Bar": "no"
}
]
這僅僅觸及了jq
的功能的表面。它是一個非常強大的工具,用於在shell 中序列化數據,它以經典的Unix 風格編譯為單個可執行二進製文件,很可能可以通過您的發行版的包管理器獲得它,並且它有很好的文檔記錄。請訪問其git
-頁親自看看。
順便說一句,處理分層資料的另一種方法json
- 至少了解您正在使用的內容 - 可能是採用另一種方式並使用符號.dot
來突破全部值在全部級別如:
printf %s "$json" | jq '..'
{
"Reservations": {
"OwnerId": "1345345",
"Groups": [],
"SecurityGroups": [
{
"Foo": "yes",
"Bar": "no"
}
]
}
}
{
"OwnerId": "1345345",
"Groups": [],
"SecurityGroups": [
{
"Foo": "yes",
"Bar": "no"
}
]
}
"1345345"
[]
[
{
"Foo": "yes",
"Bar": "no"
}
]
{
"Foo": "yes",
"Bar": "no"
}
"yes"
"no"
但更好的方法可能是僅使用jq
為各種類型的節點提供的眾多發現或搜尋方法中的一種。
答案2
這是對你的目標的答案,但不是你的問題。這意味著您無需使用 JSON 解析器即可實現您的目標。
AWS cli util 能夠僅使用參數輸出選擇欄位--query
。這是有記錄的這裡。
例如:
$ aws ec2 describe-instances \
--query 'Reservations[0].Instances[0].SecurityGroups[0].GroupName' \
--instance-id i-6b272337 \
--output text
mongodb
如果您願意,甚至可以選擇多個欄位:
$ aws ec2 describe-instances \
--query 'Reservations[0].Instances[0].SecurityGroups[0].[GroupName,GroupId]' \
--instance-id i-6b272337 \
--output text
mongodb sg-710ffa14
您也可以顯示多個符合的結構:
$ aws ec2 describe-instances \
--query 'Reservations[0].Instances[0].SecurityGroups[*].[GroupName,GroupId]' \
--instance-id i-6b272337 \
--output text
mongodb sg-710ffa14
default sg-a0243bcc