Kerem
Kerem

Reputation: 11

How to get complex structure from string?

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?

Upvotes: 1

Views: 71

Answers (2)

Syed Shahzer
Syed Shahzer

Reputation: 346

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

Upvotes: 1

Mureinik
Mureinik

Reputation: 311843

One option is to use literal_eval:

from ast import literal_eval
result = literal_eval(my_string)

Upvotes: 2

Related Questions