我试图解析从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=文本表示)?
你有多种选择。
您可以使用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
使用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']);"
如果有人只想从简单的JSON对象中提取值,而不需要嵌套结构,那么甚至不需要离开Bash就可以使用正则表达式。
下面是我使用基于JSON标准的bash正则表达式定义的函数:
function json_extract() {
local key=$1
local json=$2
local string_regex='"([^"\]|\\.)*"'
local number_regex='-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?'
local value_regex="${string_regex}|${number_regex}|true|false|null"
local pair_regex="\"${key}\"[[:space:]]*:[[:space:]]*(${value_regex})"
if [[ ${json} =~ ${pair_regex} ]]; then
echo $(sed 's/^"\|"$//g' <<< "${BASH_REMATCH[1]}")
else
return 1
fi
}
注意:对象和数组不支持作为值,但支持标准中定义的所有其他值类型。另外,只要具有完全相同的键名,无论对在JSON文档中有多深,都将匹配。
以OP为例:
$ json_extract text "$(curl 'http://twitter.com/users/username.json')"
My status
$ json_extract friends_count "$(curl 'http://twitter.com/users/username.json')"
245