简体   繁体   中英

how to convert json to model in python3

i am trying convert json string to model

then it is easy to get value with .

i have checked another question

but different, my json sting looks like,

{
   "id":"123",
   "name":"name",
   "key":{
      "id":"345",
      "des":"des"
    },
}

i prefer to use 2 class like,

class A:
    id = ''
    name = ''
    key = new B()


class B:
    id = ''
    des = ''

There are few libraries that might help:

For easier cases you can also use something from standard library like

In order to do that you should provide your custom callback as an object_hook argument to the json.loads function.

object_hook is an optional function that will be called with the result of any object literal decode (a dict ). The return value of object_hook will be used instead of the dict . This feature can be used to implement custom decoders (eg JSON-RPC class hinting).

Consider using collections.namestuple subclasses:

json_str = '''
{
   "id":"123",
   "name":"name",
   "key":{
      "id":"345",
      "des":"des"
    }
}'''

B = collections.namedtuple('B', 'id des')
A = collections.namedtuple('A', 'id name key')

def make_models(o):
    if 'key' in o:
        return A(o['id'], o['name'], B(id=o['key']['id'], des=o['key']['des']))
    else:
        return o

result = json.loads(json_str, object_hook=make_models)

print(type(result))    # outputs: <class '__main__.A'>
print(result.id)       # outputs: 123
print(result.key.id)   # outputs: 345

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM