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

3 Answers 3

2

There are few libraries that might help:

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

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

2 Comments

of course you will first need to parse json
thanks @code22 can you give me some libs support 3.6?
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).

Comments

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

3 Comments

how if i got heaps of properties, i am new to python, and on python 3.6 , thanks
as you saw collections.namedtuple('B', 'id des') : id and des are properties. Add new properties in same way
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.