I'm working on getting complex data structure as "dictionary of list of dictionaries" from a string like that:
{
"a":[ {"YY":1, "ZZ":43, "GG":22}, {"YY":33, "ZZ":23, "GG":2}],
"b":[ {"YY":1, "ZZ":43, "GG":22}, {"YY":33, "ZZ":23, "GG":2}, {"YY":33, "ZZ":23, "GG":2}],
.
.
.
}
How can I do that?
CodePudding user response:
One option is to use literal_eval
:
from ast import literal_eval
result = literal_eval(my_string)
CodePudding user response:
You can use python's built-in json
library for this.
Here is a snippet from python shell.
>>> import json
>>> complex_structure=json.loads('{"a":[ {"YY":1, "ZZ":43, "GG":22}, {"YY":33, "ZZ":23, "GG":2}],"b":[ {"YY":1, "ZZ":43, "GG":22}, {"YY":33, "ZZ":23, "GG":2}, {"YY":33, "ZZ":23, "GG":2}]}')
>>> complex_structure
{'a': [{'YY': 1, 'ZZ': 43, 'GG': 22}, {'YY': 33, 'ZZ': 23, 'GG': 2}], 'b': [{'YY': 1, 'ZZ': 43, 'GG': 22}, {'YY': 33, 'ZZ': 23, 'GG': 2}, {'YY': 33, 'ZZ': 23, 'GG':
2}]}
>>> type(complex_structure)
<class 'dict'>