【发布时间】:2019-04-10 15:02:46
【问题描述】:
首先,任何不包含经纬度的对象都将被过滤掉。我将输入一个包含以下输入 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"]]"
【问题讨论】:
-
那个循环没有做任何事情有几个原因。而你不需要它。使用您当前的代码,您应该已经完成了 99% 的工作,不是吗?唯一缺少的应该是数字仍然是字符串,而不是浮点数,对吧?