gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:43:00 25 4
gpt4 key购买 nike

我有一个 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'

关于python - 如何处理下载的 json 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15433341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com