Reputation: 61
I just started yesterday working with TCL. And i am trying to get the longitude and latitude from a call to the google maps API. I am using the following URL (with my key ofcourse) https://maps.googleapis.com/maps/api/geocode/json?address=amsterdam&key=[MYKEY]
The return is json and i convert this with json2dict. This give me a dict with only "results" and "status" as keys.
How am i going to get the long and lat from the results? I tried the dict filter, but i cant really get it to work
set lat [dict filter $dict {k v} {expr {$k eq "lat"}}]
In javascript it would be as easy as something like this
result[0].geometry.bounds.lat
Upvotes: 2
Views: 445
Reputation: 3434
result[0].geometry.bounds.lat
You can have the same benefits (and many more goodies) using tdom's JSON support:
% package req tdom
0.9.1
% set js {{"result":[{"geometry":{"bounds":{"lat":42,"long":24}}}]}}
{"result":[{"geometry":{"bounds":{"lat":42,"long":24}}}]}
% set d [dom parse -json $js]
domDoc0x7fc98b700770
% $d selectNodes {string(//result/*[1]/geometry/bounds/long)}
24
% $d selectNodes {string(//result/*[1]/geometry/bounds/lat)}
42
This assumes that you have tdom 0.9+. XPath positional access is one-based.
Upvotes: 1
Reputation: 246847
I'm guessing a bit at your json structure, hence the structure of the dict, but it's probably something like this:
package req json
set js {{"result":[{"geometry":{"bounds":{"lat":42,"long":24}}}]}}
set d [json::json2dict $js]
then
set results [dict get $d result]
set item [lindex $results 0]
set lat [dict get $item geometry bounds lat] ;# => 42
or, in one line
set lat [dict get [lindex [dict get $d result] 0] geometry bounds lat]
ok, downloaded and build rl_json
$ sudo apt install tcl-dev
$ git clone https://github.com/RubyLane/rl_json.git
$ cd rl_json
$ ./configure && make && sudo make install
then
$ tclsh
% package require rl_json
0.9.11
% set js {{"result":[{"geometry":{"bounds":{"lat":42,"long":24}}}]}}
{"result":[{"geometry":{"bounds":{"lat":42,"long":24}}}]}
% json get $js result
invalid command name "json"
% rl_json::json
Wrong # of arguments. Must be "method ?arg ...?"
% namespace import rl_json::json
% json get $js result
{geometry {bounds {lat 42 long 24}}}
% json get $js result 0
geometry {bounds {lat 42 long 24}}
% json get $js result 0 geometry bounds lat
42
Pretty straightforward.
Upvotes: 4