【问题标题】:How to use JSON data to output a formatted nested array?如何使用 JSON 数据输出格式化的嵌套数组?
【发布时间】: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% 的工作,不是吗?唯一缺少的应该是数字仍然是字符串,而不是浮点数,对吧?

标签: python json


【解决方案1】:

使用列表推导

例如:

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"]]

【讨论】:

  • 不是还要解析url中的JSON数据吗?
  • 我以上面为例...在你的情况下response1 == response
猜你喜欢
  • 2019-02-26
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 2021-07-23
  • 2016-05-18
相关资源
最近更新 更多