python中json字符串转object

import json
from collections import namedtuple

if __name__ == '__main__':
data = '{"name":"John Smith","hometown": {"name":"New York","id": 123}}'

# Parse JSON into an object with attributes corresponding to dict keys.
x = json.loads(data, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
print(x.name, x.hometown.name, x.hometown.id)
posted @ 2021-08-10 10:06  邱明成  阅读(956)  评论(0编辑  收藏  举报