2015-11-08 68 views
0

我正在尝试获取json数组的值,但我无法获得叶的值,任何人都可以帮助我吗?在Bash中解析JSON

下面是maps.googleapis.com/maps/api

的JSON我想获得持续文字和价值,这里是我一直使用的脚本。

function jsonValue() { 
KEY=$1 
num=$2 
awk -F"[,:}]" '{for(i=1;i<=NF;i++){if($i~/'$KEY'\042/){print $(i+1)}}}' | tr -d '"' | sed -n ${num}p 
} 

curl --get --include 'http://maps.googleapis.com/maps/api/directions/json?origin=59.94473,30.294254&destination=59.80612,30.308552&sensor=false&departure_time=1346197500&mode=transit&format=json' | jsonValue duration["value"] 2 

由于提前,
雷米。

+3

你真的不希望使用猛砸解析结构化语言,尤其是当API不是你的控制之下。您是否尝试过Python,Java或Ruby?它们都对结构化数据语言提供了极好的支持。 – l0b0

+0

请参阅:[如何在Linux中解析JSON与shell脚本?](http://unix.stackexchange.com/q/121718/74329) – Cyrus

回答

4

您正在寻找jq (一种轻巧灵活的命令行JSON处理器)。

+0

该工具似乎是正确的。现在,如何实现OP的目标? – whoan

+1

示例:'wget -qO - 'http://maps.googleapis.com/maps/api/directions/json?origin=59.94473,30.294254&destination=59.80612,30.308552&sensor=false&departure_time=1346197500&mode=transit'| jq'.routes []。legs []。steps []。duration [“value”]'' – Cyrus

0

这为我工作

curl -G -k --data "origin=59.94473,30.294254&destination=59.80612,30.308552&sensor=false&departure_time=1346197500&mode=transit" http://maps.googleapis.com/maps/api/directions/json | jq '.routes[].legs[].duration["text"]'