0

I'm getting data back from a library. How do I get both the keys and the data in JSON format?

It appears to not have a dict property, so I don't know how to inspect it. vars(obj.rect), fails.

I feel like this must be something super-simple -- I can see the properties (left, right, etc.), but when json just dumps the values, not the keys.

[Edit] user2357112 pointed me in the right direction, so I'm halfway there. Rect is a namedTuple, printing the json works by adding asdict(), but polygon is a array, how do I encode that as json? Obviously, I can loop through, but there must be a more generic way.

    print('Rect : ', obj.rect)
    print('rect.json : ', json.dumps(obj.rect._asdict()))
    print('polygon : ', obj.polygon)
    # polygon is an array of named tuples, so this fails.
    print('polygon.json : ', json.dumps(obj.polygon, skipkeys=False))
Rect :  Rect(left=2264, top=1031, width=241, height=238)
Rect.json :  {'left': 2264, 'top': 1031, 'width': 241, 'height': 238}
polygon :  [Point(x=2260, y=131), Point(x=2261, y=367), Point(x=2500, y=360), Point(x=2502, y=119)]
polygon.json :  [[2260, 131], [2261, 367], [2500, 360], [2502, 119]]

Obviously, skipKeys isn't the answer. I've hacked away with .dict, but that's not working. I'm new to python, so not even sure how to debug what Rect and Polygon are.

Tac Tacelosky
  • 3,165
  • 3
  • 27
  • 28

0 Answers0