0

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 = ''
Community
  • 1
  • 1
dianyi
  • 105
  • 1
  • 6

3 Answers3

2

There are few libraries that might help:

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

code22
  • 133
  • 5
1

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 (e.g. JSON-RPC class hinting).

mic4ael
  • 7,974
  • 3
  • 29
  • 42
1

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
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • how if i got heaps of properties, i am new to python, and on python 3.6 , thanks – dianyi Mar 18 '17 at 13:26
  • as you saw `collections.namedtuple('B', 'id des')` : `id` and `des` are properties. Add new properties in same way – RomanPerekhrest Mar 18 '17 at 13:30
  • yes, i got what you mean, but some times the key from json is a keyword, like `class` or `str`, and how about i got 100 properties. – dianyi Mar 18 '17 at 13:39