Home > database >  python unable to get dictionary from string
python unable to get dictionary from string

Time:02-27

I have a subprocess that prints a string that I would like to use as a dictionary.

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

I am decoding the output using.

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

Why am I unable to use it as a dictionary? d['name'] returns TypeError: string indices must be integers

Does anyone know what is going on? Is it some kind of encoding issue?

Cheers, Chris

CodePudding user response:

Use the inbuilt json module; speficially, json.loads().

json.loads() inputs a string/text object and returns a Python dictionary. JSON's syntax uses double quotes for keys and values, however, so you'd need to reformat your string to use double quotes instead of single quotes:

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

Then we can use the json module:

import json

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

Which will result:

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