Hallo,
Im trying to handle a nested JSON Data without success.
Given http://api.zippopotam.us/us/ma/belmont/ the output is the following:
{
"country abbreviation": "US",
"places": [
{
"place name": "Belmont",
"longitude": "-71.4594",
"post code": "02178",
"latitude": "42.4464"
},
{
"place name": "Belmont",
"longitude": "-71.2044",
"post code": "02478",
"latitude": "42.4128"
}
],
"country": "United States",
"place name": "Belmont",
"state": "Massachusetts",
"state abbreviation": "MA"
}
In Python (w/ requests), I can do something like:
import requests
r = requests.get('http://api.zippopotam.us/us/ma/belmont')
j = r.json()
print(j['state'])
print(len(j['places']))
for each in j['places']:
print(each['latitude'])
And I have the result:
Massachusetts
2
42.4464
42.4128
Pls how can I do that in Nim ?
Cheers
You can use the httpclient and json modules, and the rest of the code is almost identical:
import httpclient, json
var client = newHttpClient()
var res = client.getContent("http://api.zippopotam.us/us/ma/belmont")
var j = parseJson(res)
echo j["state"]
echo j["places"].len
for each in j["places"]:
echo each["latitude"]
Regards
Look for json and httpclient module
import json, httpclient
var
url = "http://api.zippopotam.us/us/ma/belmont"
client = newHttpClient()
content = client.getContent(url).parseJson
state = content["state"]
places = content["places"]
echo state.getStr
echo places.len
for place in places.items:
echo place["latitude"].getStr