在 Bash 中解析 JSON
Aashish Sunuwar 2023年1月30日 Bash 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