我试图解析从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]
不幸的是,使用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
你有多种选择。
您可以使用trdsql[1]来解析和转换JSON/CSV输入。以你为榜样;
trdsql "select attr1,attr2 from sample.json"
你也可以像SQL一样使用where子句。输出在CSV, JSON等。非常方便的工具。
根据我的经验,trdsql在处理属性嵌套值时有点问题,所以我在适当的时候使用qp[2]找到了一个解决方案。
cat sample.json | qp 'select attr1, attr2.detail.name where attr3=10'
注意这里没有FROM。
为了查看结果,您可以使用超快速命令行json查看器工具jless来查看输出[3]。
Clickhouse来了个新人。您可以从[4]中看到它的功能。
https://github.com/noborus/trdsql
https://jless.io
https://github.com/f5io/qp
https://clickhouse.com/blog/extracting-converting-querying-local-files-with-sql-clickhouse-local
使用node . js
如果系统安装了Node.js,则可以在JSON中使用-p print和-e evaluate脚本标志。解析以提取所需的任何值。
一个简单的例子,使用JSON字符串{"foo": "bar"}并取出"foo"的值:
node -pe 'JSON.parse(process.argv[1]).foo' '{ "foo": "bar" }'
输出:
bar
因为我们可以访问cat和其他实用程序,我们可以对文件使用这个:
node -pe 'JSON.parse(process.argv[1]).foo' "$(cat foobar.json)"
输出:
bar
或包含JSON的URL等任何其他格式:
node -pe 'JSON.parse(process.argv[1]).name' "$(curl -s https://api.github.com/users/trevorsenior)"
输出:
Trevor Senior