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

标签 python json string dictionary filter

我在 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

关于Python - 过滤字典 JSON 响应以仅发回两个值或转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39758835/

相关文章:

Python SFTP 问题

javascript - 回调数据不被识别

javascript - 将视频源对象推送到 Jwplayer Multiple Sources 对象

javascript - 将 JavaScript split()-slice()-join() 序列转换为 C++

php - 我需要从 php 运行 python 脚本

python - 无效的帖子 : 400 - Bad Request with Python requests

javascript - JS : Random String without Repeating Same String Twice

string - 如何检测字符串中的字符是大写还是小写?

python - 计算 Pandas 子组的百分比

json - Golang bson structs - 对 json 中的单个字段使用多个字段名称,但只有一个用于写入数据库