Skip to main content
 首页 » 编程设计

Python之过滤字典 JSON 响应以仅发回两个值或转换为字符串

2025年05月04日25cyq1162

我在 Python 中操作一个调用 API 并在 JSON 中获得有效结果的 URL。

我只需要[result]提供的'latitude'和'longitude'

但是,我似乎找不到任何处理返回字典值的好方法。

我尝试将 JSON 转换为字符串,但由于我的最终目标是将纬度和经度附加到另一个 URL,这似乎很愚蠢?

一直在搜索,似乎解析 DICT 是一个常见问题。

谁能指出我正确的方向?

我的代码(运行)

import urllib2 
import json 
Postcode = raw_input("Hello hello hello, what's your postcode..?  ") 
PostcodeURL = 'https://api.postcodes.io/postcodes/' + Postcode 
json_str = urllib2.urlopen(PostcodeURL).read() 
d = json.loads(json_str) 
print(d) 

输出看起来像这样:

{u'status': 200, u'result': {u'eastings': 531025, u'outcode': u'N8', u'admin_county': None, u'postcode' 

请您参考如下方法:

你得到了一个嵌套字典,所以使用正确的键访问它的值:

d = json.loads(json_str) 
lat, long = d['result']['latitude'], d['result']['longitude'] 
newurl = url + '?' + 'lat=' + lat + '&lon=' + lon