Python 将字典转换为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26745519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:58:25  来源:igfitidea点击:

Converting dictionary to JSON

pythonjsonpython-2.7dictionary

提问by sheetal_158

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

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

我无法访问 JSON 中的数据。我究竟做错了什么?

TypeError: string indices must be integers, not str

采纳答案by Iman Mirzadeh

json.dumps()converts a dictionary to strobject, not a json(dict)object! So you have to load your strinto a dictto use it by using json.loads()method

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

See json.dumps()as a save method and json.loads()as a retrieve method.

json.dumps()的保存方法,并json.loads()作为检索方法。

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

回答by Tim

json.dumps()returns the JSON string representation of the python dict. See the docs

json.dumps()返回 python 字典的 JSON 字符串表示。查看文档

You can't do r['rating']because r is a string, not a dict anymore

你不能这样做,r['rating']因为 r 是一个字符串,而不是一个字典了

Perhaps you meant something like

也许你的意思是

r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))

回答by user3273866

No need to convert it in a string by using json.dumps()

无需使用将其转换为字符串 json.dumps()

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

You can get the values directly from the dict object.

您可以直接从 dict 对象中获取值。

回答by Aslan

Defining r as a dictionary should do the trick:

将 r 定义为字典应该可以解决问题:

>>> r: dict = {'is_claimed': 'True', 'rating': 3.5}
>>> print(r['rating'])
3.5
>>> type(r)
<class 'dict'>