Strange JSON syntax behavior embedded in objects using object_hook

I was exploring a json library and trying to convert an object to JSON data and vice versa. I ran into difficulties running this sample code:

import json

class Obj:
    '''
    classdocs
    '''

    def __init__(self,s,hello="Hello world!"):
        '''
        Constructor
        '''
        self.s = s
        self.hello = hello
    def __repr__(self):
        return '<MyObj(%s,%s)>' % (self.s, self.hello)

def objToJSON(obj):
    return obj.__dict__

def jSONToObj(json):
    print(json)
    return Obj(**json)

if __name__ == '__main__':
    str = json.dumps(Obj("Hello","World"), default=objToJSON, sort_keys=True)
    print(str)
    print(json.loads(str,object_hook=jSONToObj))
    str = json.dumps(Obj("Text",{"a":"aaaa","b":"BBBBB","C":"ccccc"}), default=objToJSON, sort_keys=True)
    print(str)
    print(json.loads(str,object_hook=jSONToObj))

The output of which:

{"hello": "World", "s": "Hello"}
{'s': 'Hello', 'hello': 'World'}
<MyObj(Hello,World)>
{"hello": {"C": "ccccc", "a": "aaaa", "b": "BBBBB"}, "s": "Text"}
{'a': 'aaaa', 'C': 'ccccc', 'b': 'BBBBB'}
Traceback (most recent call last):
  File "C:\Users\dimo414\src\test.py", line 27, in <module>
    print(json.loads(str,object_hook=jSONToObj))
  File "C:\Python31\lib\json\__init__.py", line 318, in loads
    return cls(**kw).decode(s)
  File "C:\Python31\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python31\lib\json\decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
  File "C:\Users\dimo414\src\test.py", line 22, in jSONToObj
    return Obj(**json)
TypeError: __init__() got an unexpected keyword argument 'a'

It appears that when the dictionary is a value in the object dictionary, the data passed to jSONToObj is an internal dictionary, not a complete dictionary. Why is this?

+3
source share
1 answer

Since you indicated that objects should be restored using a function jSONToObj, the deserializer assumes that all dicts must be objects and tries to call your deserializer on them.

From the docs:

object_hook (a dict). object_hook dict. (, JSON-RPC ).

dict - , , , loads . , .

+3

Source: https://habr.com/ru/post/1789923/


All Articles