省市区json转list
时间: 2023-09-05 15:14:28 浏览: 105
省市区Json
5星 · 资源好评率100%
可以通过以下方式将省市区的JSON数据转换为列表:
```python
import json
def json_to_list(data):
result = []
for item in data:
province = item['name']
cities = item['cities']
for city in cities:
city_name = city['name']
districts = city['districts']
district_names = [district['name'] for district in districts]
result.append((province, city_name, district_names))
return result
# 示例的省市区JSON数据
json_data = '''
[
{
"name": "北京市",
"cities": [
{
"name": "北京市",
"districts": [
{"name": "东城区"},
{"name": "西城区"},
{"name": "朝阳区"},
{"name": "丰台区"},
{"name": "石景山区"},
{"name": "海淀区"},
{"name": "门头沟区"},
{"name": "房山区"},
{"name": "通州区"},
{"name": "顺义区"},
{"name": "昌平区"},
{"name": "大兴区"},
{"name": "怀柔区"},
{"name": "平谷区"},
{"name": "密云县"},
{"name": "延庆县"}
]
}
]
},
{
"name": "上海市",
"cities": [
{
"name": "上海市",
"districts": [
{"name": "黄浦区"},
{"name": "徐汇区"},
{"name": "长宁区"},
{"name": "静安区"},
{"name": "普陀区"},
{"name": "虹口区"},
{"name": "杨浦区"},
{"name": "闵行区"},
{"name": "宝山区"},
{"name": "嘉定区"},
{"name": "浦东新区"},
{"name": "金山区"},
{"name": "松江区"},
{"name": "青浦区"},
{"name": "奉贤区"},
{"name": "崇明县"}
]
}
]
}
]
'''
data = json.loads(json_data)
result_list = json_to_list(data)
# 输出结果
for item in result_list:
province, city, districts = item
print(province, city, districts)
```
上述代码将会输出:
```
北京市 北京市 ['东城区', '西城区', '朝阳区', '丰台区', '石景山区', '海淀区', '门头沟区', '房山区', '通州区', '顺义区', '昌平区', '大兴区', '怀柔区', '平谷区', '密云县',
阅读全文