将字典转换为JSON [英] Converting dictionary to JSON
本文介绍了将字典转换为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)
对象!因此,必须使用
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
将json.dumps()
作为保存方法,将json.loads()
作为检索方法.
See json.dumps()
as 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
这篇关于将字典转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文