在 Bash 中解析 JSON

Aashish Sunuwar 2023年1月30日 Bash Bash Json
  1. 在 Bash 中使用 jq(輕量級、靈活的命令列 JSON 處理工具)解析 JSON
  2. 在 Bash 中使用 grep 解析 JSON
  3. 使用 python3 解析 JSON
在 Bash 中解析 JSON

我們將學習使用不同的技術在 bash 中解析 JSON 資料。

我們將使用一個假的 JSON 伺服器作為示例。

假 JSON 伺服器 - https://jsonplaceholder.typicode.com/posts

在 Bash 中使用 jq(輕量級、靈活的命令列 JSON 處理工具)解析 JSON

jq 是一個小型跨平臺解決方案,用於以更短、更簡單、更輕鬆的方式管理 JSON 資料。

你可以從這裡下載 jq

使用 jq 獲取更漂亮的格式化 JSON 資料

jq . 命令美化了 json 資料。

curl "https://jsonplaceholder.typicode.com/posts" | jq . 

輸出:

[  {  "userId": 1,  "id": 1,  "title": "delectus aut autem",  "completed": false  },  {  "userId": 1,  "id": 2,  "title": "quis ut nam facilis et officia qui",  "completed": false  },  {  "userId": 1,  "id": 3,  "title": "fugiat veniam minus",  "completed": false  }  ... // remaining list of data ] 

從 JSON 獲取特定欄位的值

我們可以使用 jq.[].field_name 從 JSON 資料陣列中獲取任何特定欄位的值。

curl "https://jsonplaceholder.typicode.com/posts" | jq '.[].id' 

輸出:

1 2 3 ... 

從 JSON 中獲取第一個專案的標題

curl "https://jsonplaceholder.typicode.com/posts" | jq '.[0].title' 

輸出:

"delectus aut autem" 

在 Bash 中使用 grep 解析 JSON

grep 命令也可用於解析 JSON 資料。

示例 JSON 檔案:

[  {  "id": 1,  "name": "Andres Gustov",  "email": "andddy7@gmail.com"  },  {  "id": 2,  "name": "Anthony Marklov",  "email": "antman33@gmail.com"  } ] 

示例指令碼:

grep -o '"email": "[^"]*' examplejsonfile.json | grep -o '[^"]*$' 

我們使用 -o 選項僅選擇與給定模式匹配的行。然後,我們指定模式'"email": "[^"]*',這意味著我們想要鍵 email 的所有值。之後,我們傳遞 JSON 檔案來查詢模式。最後,我們使用另一個 grep -o 命令將結果通過管道輸出,以刪除除值之外的所有內容。

輸出:

andddy7@gmail.com antman33@gmail.com 

使用 python3 解析 JSON

我們還可以使用 python 的 json 模組來處理 JSON 操作。

curl -s 'https://jsonplaceholder.typicode.com/posts' | \  python3 -c "import sys, json; print(json.load(sys.stdin))" 

獲取特定欄位值

curl "https://jsonplaceholder.typicode.com/posts" | \  python3 -c "import sys, json; data=json.load(sys.stdin); print([d['id'] for d in data])" 

輸出:

1 2 3 ... 

獲取第一個專案的標題

curl "https://jsonplaceholder.typicode.com/posts" | \  python3 -c "import sys, json; print(json.load(sys.stdin)[0]['title'])" 

輸出:

"delectus aut autem" 
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe