Skip to main content
 首页 » 编程设计

python之如何处理下载的 json 字符串

2025年05月04日28JustinYoung

我有一个 json 字符串,我试图通过在 tkinter GUI 窗口上使用标签来打印每个部分(id、名称、链接等)。

数据:

{"id":"123456789","name":"John Smith","first_name":"John","last_name":"Smith","link":"http:\/\/www.facebook.com\/john.smith","username":"john.smith","gender":"male","locale":"en_GB"} 

代码:

URL = https://graph.facebook.com/ + user 
info = urlopen(info).read() 
json_format = infor.decode("utf-8") 

我的问题是如何将 json 数据的每个部分分配给一个变量,它可以打印在 tkinter 标签上吗?

提前致谢

编辑

试过这段代码:

jsonData = json.loads(json_format) 
u_name = jsoninfo['username'] 

得到如下错误信息

TypeError: string indices must be integers 

请您参考如下方法:

您想使用 json 标准模块:

>>> import json 
>>> data = '{"id":"123456789","name":"John Smith","first_name":"John","last_name":"Smith","link":"http:\/\/www.facebook.com\/john.smith","username":"john.smith","gender":"male","locale":"en_GB"}' 
>>> d = json.loads(data) 

这为您提供了作为常规字典使用的数据:

>>> d 
{u'username': u'john.smith', u'first_name': u'John', u'last_name': u'Smith', u'name': u'John Smith', u'locale': u'en_GB', u'gender': u'male', u'link': u'http://www.facebook.com/john.smith', u'id': u'123456789'} 
>>> d['username'] 
u'john.smith'