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.

1
  • This is not a duplicate of the indicated question. This question specifically asks about complex (nested) structures, the other does not. Commented Jan 6, 2021 at 12:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

This won't work with nested classes, nor when you don't a c'tor the takes all these arguments. I would recommend jsonpickle
@gMorphus "if they take keyword arguments matching the dictionary content"
my bad... still the rest of my comment stands.
-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.

1 Comment

This really doesn't help the OP... (also not a very good suggestion).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.