D
D
Dmustache Usakov2021-08-02 06:10:35
Python
Dmustache Usakov, 2021-08-02 06:10:35

How to get a field from JSON?

I want to get coordinates with help. this api
http://search.maps.sputnik.ru/search/addr?format=j...
I use this code to get data from "coordinates" field:

import requests
r = requests.get("http://search.maps.sputnik.ru/search/addr?format=json&lat&q=Песочная+аллея,+дом+1")
data = r.json()
geo = data.get('coordinates')
print(geo)


But I can't get anything

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Kuts, 2021-08-02
@Dmustache

Because there the way is more difficult:

import requests
r = requests.get("http://search.maps.sputnik.ru/search/addr?format=json&lat&q=Песочная+аллея,+дом+1")
print(r.json()['result']['address'][0]['features'][0]['geometry']['geometries'][0]['coordinates'])
# [37.674698, 55.79341]

Alternatively, you can run the recursion and pull out all the keys with 'coodinates':
coordinates = []

def search_key(data, key):
    if isinstance(data, list):
        for x in data:
            search_key(x, key)
    if isinstance(data, dict):
        for x in data.keys():
            if x == key:
                coordinates.append(data[x])
            else:
                search_key(data[x], key)

search_key(r.json(), 'coordinates')
print(coordinates)
# 

I
Ivan Semenov, 2021-08-15
@semenovs

import requests

url = "http://search.maps.sputnik.ru/search/addr"
params = {'format': 'json', 'q': 'Песочная аллея, дом 1'}
rq = requests.get(url=url, params=params)
location = rq.json()['result']['viewport'].values()
print(list(location)[0:2])

61185ce8d0ea7765523774.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question