Python JSON decodes getting invalid value

I have a JSON decoder configured with a special decoder function:

data.tankDecoder = JSONDecoder(object_hook=tankFromJSON)

tankFromJSON:

def tankFromJSON(obj):
    print("object", obj)
    humans = [HumanFish(human["name"], human["position"][0],
                        human["position"][1], human["size"])
              for human in obj["humans"]]
    bots = [RobotFish(bot["position"][0], bot["position"][1], bot["size"])
            for bot in obj["bots"]]
    tank = Tank(obj["canvasSize"], humans)
    tank.grass = obj["grass"]
    tank.bots = bots
    print(tank) 
    return tank

JSON I get looks something like this:

{
    "canvasSize": 600,
    "newBotOffset": 50,
    "grass": [
        [583, 588],
        ...,
        [409, 575],
        [496, 574]
    ],
    "bots": [],
    "humans": [{
        "name": ["127.0.0.1", 50014],
        "acceleration": [0, 0],
        "maxSpeed": 3,
        "speed": [0, 0],
        "accelerationRate": 1,
        "position": [300.0, 300.0],
        "foodHistory": [],
        "efficiency": 0.4,
        "size": 20,
        "color": "green"
    }],
    "maxBots": 20
}

For some reason, the value objin the function tankFromJSONbecomes the first dictionary in the list humansinstead of all JSON itself.

Can anyone explain?

+4
source share
1 answer

When decoding, the hook object is called once for each JSON object that occurs. What you see is that the hook is first called to internal objects, and then to external objects when deserialization is unwound.

, JSON , , , , :

s = '''
{
    "outer": {
        "middle": {
            "inner": [1, 2, 3]
        }
    }
}
'''

def hook(obj):
    print(obj)
    return obj

decoder = JSONDecoder(object_hook=hook)
decoder.decode(s)

:

{'inner': [1, 2, 3]}
{'middle': {'inner': [1, 2, 3]}}
{'outer': {'middle': {'inner': [1, 2, 3]}}}
+4

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


All Articles