0

I'm trying to get the value of a json array but I don't manage to get the value of a leaf, can anyone help me?

Here's the json from maps.googleapis.com/maps/api

I'd like to get the duration text and value and here's the script I've been using so far.

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

Thanks in advance,
Jeremie.

H. Pauwelyn
  • 13,575
  • 26
  • 81
  • 144
Jérémie Zarca
  • 105
  • 1
  • 9
  • 3
    You really don't want to use Bash to parse structured languages, especially if the API is not under your control. Have you tried Python, Java, or Ruby? They all have excellent support for structured data languages. – l0b0 Nov 08 '15 at 10:12
  • See: [How to parse JSON with shell scripting in Linux?](http://unix.stackexchange.com/q/121718/74329) – Cyrus Nov 08 '15 at 10:17

2 Answers2

5

You are looking for jq (a lightweight and flexible command-line JSON processor).

Ole Tange
  • 31,768
  • 5
  • 86
  • 104
  • 1
    The tool seems the right one. Now, how to achieve what the OP is looking for? – whoan Nov 08 '15 at 10:21
  • 1
    Example: `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 Nov 08 '15 at 10:48
0

This worked for me

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"]'
Jérémie Zarca
  • 105
  • 1
  • 9