Reputation: 1
I have tried different options to convert a string to dictionary.
My string looks like this:
{'severity_label': 'Major', 'ne_reported_time': 1475424546, 'node_id': 54357, 'prob_cause_string': None}
When i use
a_dict = dict([x.strip('{}').split(":"),])
it gives me an error:
Traceback (most recent call last):
File "<pyshell#168>", line 1, in <module>
a_dict = dict([x.strip('{}').split(":"),])
ValueError: dictionary update sequence element #0 has length 121; 2 is required
I am running this on Python3. Also tried various other options things not working. Any help appreciated.
Upvotes: 0
Views: 1300
Reputation: 2252
Why not to use Python 3's inbuilt ast library's function literal_eval. It is better to use literal_eval instead of eval
import ast
str_of_dict = "{'key1': 'key1value', 'key2': 'key2value'}"
ast.literal_eval(str_of_dict)
will give output as actual Dictionary
{'key1': 'key1value', 'key2': 'key2value'}
This is easy as you like.
Upvotes: 1
Reputation: 33407
Actually this is not JSON. This is a representation of a python object (like using the repr
function).
The most safe way to convert this back to a python object is to use the ast.literal_eval
function.
Upvotes: 1
Reputation: 3477
You should use json.loads
import json
a = '{"severity_label": "Major", "ne_reported_time": 1475424546, "node_id": 54357, "prob_cause_string": null}'
d = json.loads(a)
Note I replaced ' by " and None by null
Upvotes: 0
Reputation: 36472
That string really is valid JSON, I think. Just use the json.loads
functionality to get a dictionary.
Upvotes: -1