我试图解析从curl请求返回的JSON,就像这样:
curl 'http://twitter.com/users/username.json' |
sed -e 's/[{}]/''/g' |
awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}'
上面将JSON划分为多个字段,例如:
% ...
"geo_enabled":false
"friends_count":245
"profile_text_color":"000000"
"status":"in_reply_to_screen_name":null
"source":"web"
"truncated":false
"text":"My status"
"favorited":false
% ...
我如何打印一个特定的字段(由-v k=文本表示)?
你可以使用bashJson
它是Python JSON模块的包装器,可以处理复杂的JSON数据。
让我们考虑来自test.json文件的示例JSON数据
{
"name":"Test tool",
"author":"hack4mer",
"supported_os":{
"osx":{
"foo":"bar",
"min_version" : 10.12,
"tested_on" : [10.1,10.13]
},
"ubuntu":{
"min_version":14.04,
"tested_on" : 16.04
}
}
}
下面的命令从这个示例JSON文件读取数据
./bashjson.sh test.json name
打印:测试工具
./bashjson.sh test.json supported_os osx foo
打印:酒吧
./bashjson.sh test.json supported_os osx tested_on
打印:[10.1,10.13]
使用Python的JSON支持,而不是使用AWK!
就像这样:
curl -s http://twitter.com/users/username.json | \
python -c "import json,sys;obj=json.load(sys.stdin);print(obj['name']);"
macOS v12.3 (Monterey)删除了/usr/bin/python,因此对于macOS v12.3及更高版本,我们必须使用/usr/bin/python3。
curl -s http://twitter.com/users/username.json | \
python3 -c "import json,sys;obj=json.load(sys.stdin);print(obj['name']);"
不幸的是,使用grep的得票最多的答案返回完整的匹配,这在我的场景中不起作用,但如果您知道JSON格式将保持不变,您可以使用向后和向前查找来提取所需的值。
# echo '{"TotalPages":33,"FooBar":"he\"llo","anotherValue":100}' | grep -Po '(?<="FooBar":")(.*?)(?=",)'
he\"llo
# echo '{"TotalPages":33,"FooBar":"he\"llo","anotherValue":100}' | grep -Po '(?<="TotalPages":)(.*?)(?=,)'
33
# echo '{"TotalPages":33,"FooBar":"he\"llo","anotherValue":100}' | grep -Po '(?<="anotherValue":)(.*?)(?=})'
100