2

I need to convert json string to python object. for example,

{
"person":{
    "name":"aa",
    "age":"12",
    "address":{
        "city":"cc",
        "road":"kk"
    }

    }    
}

there are two python class Person and Address used to generate python object. but I don't know how to map it.

Jay
  • 1,317
  • 4
  • 16
  • 40
NOrder
  • 2,483
  • 5
  • 26
  • 44
  • This is not a duplicate of the indicated question. This question specifically asks about complex (nested) structures, the other does not. – AdamAL Jan 06 '21 at 12:53

2 Answers2

1

You can easily convert the JSON string to a native Python dictionary with json.loads:

import json

d = json.loads(s)

It is not clear what arguments your Person and Address take, but if they take keyword arguments matching the dictionary content it could be as simple as:

d['address'] = Address(**d['address'])
p = Person(**d)

Where ** unpacks the dictionary into keyword arguments.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • This won't work with nested classes, nor when you don't a c'tor the takes all these arguments. I would recommend [jsonpickle](http://jsonpickle.github.io/) – Guy Aug 08 '16 at 06:16
  • @gMorphus *"if they take keyword arguments matching the dictionary content"* – jonrsharpe Aug 08 '16 at 06:17
  • my bad... still the rest of my comment stands. – Guy Aug 08 '16 at 19:23
-3

You can do this in a couple ways. One way is the simplejson literal translation. I would say the cleanest way of creating an extensible method is creating a class with that same structure.

sahutchi
  • 2,223
  • 2
  • 19
  • 20