我试图解析从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=文本表示)?
如果你安装了PHP解释器:
php -r 'var_export(json_decode(`curl http://twitter.com/users/username.json`, 1));'
例如:
我们有一个资源,提供JSON内容与国家的ISO代码:http://country.io/iso3.json,我们可以很容易地看到它在一个shell与curl:
curl http://country.io/iso3.json
但它看起来不是很方便,也不容易读。更好地解析JSON内容并看到可读的结构:
php -r 'var_export(json_decode(`curl http://country.io/iso3.json`, 1));'
这段代码将打印如下内容:
array (
'BD' => 'BGD',
'BE' => 'BEL',
'BF' => 'BFA',
'BG' => 'BGR',
'BA' => 'BIH',
'BB' => 'BRB',
'WF' => 'WLF',
'BL' => 'BLM',
...
如果你有嵌套数组,这个输出看起来会更好…