在Python中将字典转换为JSON [英] Converting Dictionary to JSON in python

查看:822
本文介绍了在Python中将字典转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
file.write(str(r['rating']))

我无法在json中访问我的数据。我做错了什么?

I am not able to access my data in the json. What am I doing wrong?

TypeError: string indices must be integers, not str


推荐答案

json.dumps()转换字典对于str对象,而不是一个json(dict)对象!所以你必须将你的str加载到一个dict中,以使用 json.loads() 方法!

请参阅json.dumps()a保存方法和json.loads()作为检索方法!

这是代码示例,可能会帮助您更了解更多

json.dumps() converts a dictionary to str object,not a json(dict) object!so you have to load your str into a dict to use it by using json.loads() method!
see json.dumps() a save method and json.loads() as a retrieve method!
this is the code sample which might help you understand it more

import json

r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict

这篇关于在Python中将字典转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆