首先,任何不包含纬度和经度的对象都将被过滤掉。我将输入一个包含以下输入的JSON的URL。然后,我想解析该JSON数据,并使用该数据以[纬度,经度,位置]格式将以下内容作为JSON数组输出。我该怎么做?(注意:字符串中的纬度和经度需要转换为浮点数)
import json
import urllib.request
def getData(url):
dictionary = {}
response = urllib.request.urlopen(url)
content = response.read().decode()
response1 = json.loads(content)
for i in response1:
for element in i:
if element == 'longitude' and element == 'latitude':
float(i['longitude'])
float(i['latitude'])
dictionary.update(i)
total = [[_.get("latitude"), _.get("longitude"), _.get("location")] for _ in dictionary]
return json.dumps(total)
输入:
[{"capital": "Yes", "latitude": "35.6895", "longitude": "139.6917", "location": "Tokyo"},
{"capital": "Yes","latitude": "39.9042", "longitude": "116.4074", "location": "Beijing"},
{"capital": "No", "location": "Shanghai"}, {"capital": "No", "location":
"Osaka"}]
预期输出:
"[[35.6895, 139.6917, "Tokyo"], [39.9042, 116.4074, "Beijing"]]"
答案 0 :(得分:0)
使用列表理解
例如:
import json
response = [{"capital": "Yes", "latitude": "35.6895", "longitude": "139.6917", "location": "Tokyo"},
{"capital": "Yes","latitude": "39.9042", "longitude": "116.4074", "location": "Beijing"},
{"capital": "No", "location": "Shanghai"}, {"capital": "No", "location":
"Osaka"}]
lst = [[float(i["latitude"]), float(i["longitude"]), i["location"] ] for i in response if ("latitude" in i) and ('longitude' in i)]
print(json.dumps(lst))
输出:
[[35.6895, 139.6917, "Tokyo"], [39.9042, 116.4074, "Beijing"]]