python 将一个JSON 字典转换为一个Python 对象

时间:2023-03-10 05:20:01
python 将一个JSON 字典转换为一个Python 对象

将一个JSON 字典转换为一个Python 对象例子

>>> s='{"name":"apple","shares":50,"prices":490.11}'

>>> s

'{"name":"apple","shares":50,"prices":490.11}'

>>> from collections import OrderedDict

>>> import json

>>> data=json.loads(s,object_pairs_hook=OrderedDict)

>>> data

OrderedDict([('name', 'apple'), ('shares', 50), ('prices', 490.11)])

>>> class JSONObject:

                def __init__(self,d):

                                self.__dict__=d                               

>>> data=json.loads(s,object_hook=JSONObject)

>>> data.name

'apple'

>>> data.shares

50

>>> data.prices

490.11

>>>