我试图解析从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=文本表示)?
YAML处理器yq
考虑使用yq进行JSON处理。
yq是一个轻量级、可移植的命令行YAML处理器(JSON是YAML的一个子集)。
语法类似于jq。
输入
{
"name": "Angel",
"address": {
"street": "Stairway to",
"city": "Heaven"
}
}
用法举例1
yq e ` .name ` $FILE
Angel
用法举例二
yq有一个很好的内置特性,可以使JSON和YAML成为grep-able
yq——输出格式道具$FILE
name = Angel
address.street = Stairway to
address.city = Heaven
使用Python使用Bash
在.bashrc文件中创建一个Bash函数:
function getJsonVal () {
python -c "import json,sys;sys.stdout.write(json.dumps(json.load(sys.stdin)$1))";
}
Then
curl 'http://twitter.com/users/username.json' | getJsonVal "['text']"
输出:
My status
下面是相同的函数,但是带有错误检查。
function getJsonVal() {
if [ \( $# -ne 1 \) -o \( -t 0 \) ]; then
cat <<EOF
Usage: getJsonVal 'key' < /tmp/
-- or --
cat /tmp/input | getJsonVal 'key'
EOF
return;
fi;
python -c "import json,sys;sys.stdout.write(json.dumps(json.load(sys.stdin)$1))";
}
其中$# -ne 1确保至少有一个输入,而-t 0确保从管道重定向。
这个实现的好处是,您可以访问嵌套的JSON值并返回JSON内容!=)
例子:
echo '{"foo": {"bar": "baz", "a": [1,2,3]}}' | getJsonVal "['foo']['a'][1]"
输出:
2
如果你想要更漂亮,你可以把数据打印出来:
function getJsonVal () {
python -c "import json,sys;sys.stdout.write(json.dumps(json.load(sys.stdin)$1, sort_keys=True, indent=4))";
}
echo '{"foo": {"bar": "baz", "a": [1,2,3]}}' | getJsonVal "['foo']"
{
"a": [
1,
2,
3
],
"bar": "baz"
}