Answer the question
In order to leave comments, you need to log in
How to get (form) a hierarchical directory from the database?
In the database there is a table of addresses City-Street-House.
You need to get a hierarchy from this and get json like this:
[
{
'city': 'Moscow',
'streets': [
{
'street': 'Lomonosova',
'buildings': [
'1',
'2',
'3'
]
}
]
}
]
Answer the question
In order to leave comments, you need to log in
I think the structure of the database should not be any special for solving this problem. We just create a table, fill it with data (examples in MS SQL, but I think the essence will be clear):
Using Python, connecting to the database is not very difficult, here is a link to the article, it explains quite clearly - https://habr.com/ en/post/321510/
After getting the data from the database, it will look something like this:
result = [('Moscow', 'Ivanova', '10',) , ('Moscow', 'Ivanova', '13a',) , ('Moscow', 'Ivanova', '2') ......]
import json
import collections as col
rows_from_DB = [('Moscow','Lomonosova','14',), ('Moscow','Lomonosova','15a',), ('Omsk','Ivanova','4',), ('Moscow','Kotlyara','7',), ('Sochi','Zhukova','11b',)]
cities = col.defaultdict()
for row in rows_from_DB:
if row[0] not in cities:
cities[row[0]] = col.defaultdict()
if row[1] not in cities[row[0]]:
cities[row[0]][row[1]] = []
cities[row[0]][row[1]].append(row[2])
print(json.dumps(cities))
{
"Omsk": {
"Ivanova": ["4"]
},
"Moscow": {
"Kotlyara": ["7"],
"Lomonosova": ["14", "15a"]
},
"Sochi": {
"Zhukova": ["11"]
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question