将字典转换为JSON

问题:将字典转换为JSON

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

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

TypeError: string indices must be integers, not str
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?

TypeError: string indices must be integers, not str

回答 0

json.dumps()将字典转换为str对象,而不是json(dict)对象!因此,您必须使用方法将其加载strdictjson.loads()

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

这是代码示例,可以帮助您进一步了解它:

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.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() 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

回答 1

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

您不能这样做,r['rating']因为r是字符串,不再是dict

也许你的意思是

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

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

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

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']))

回答 2

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

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

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

No need to convert it in a string by using 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.


回答 3

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

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

Defining r as a dictionary should do the trick:

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