python 无法从字符串中获取字典

python unable to get dictionary from string

我有一个打印字符串的子进程,我想将其用作字典。

b"{'name': 'Bobby', 'age': 141}\r\n"

我正在使用解码输出。

d = p.stdout.read().decode("utf-8").strip()

为什么我无法将它用作字典? d['name'] returns TypeError: string indices must be integers

有人知道这是怎么回事吗?是某种编码问题吗?

干杯, 克里斯

使用内置的json模块;具体来说,json.loads().

json.loads() 输入一个 string/text 对象和 returns 一个 Python 字典。 JSON 的语法对键和值使用双引号,但是,因此您需要重新格式化字符串以使用双引号而不是单引号:

'{"name": "Bobby", "age": 141}\r\n'

然后我们可以使用json模块:

import json

my_string = '{"name": "Bobby", "age": 141}\r\n'
my_dic = json.loads(my_string)
print(my_dic, type(my_dic))

结果将是:

{'name': 'Bobby', 'age': 141} <class 'dict'>