将字典转换为 JSON [英] Converting dictionary to JSON

查看:43
本文介绍了将字典转换为 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() 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屋!

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