好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

深入理解Python对Json的解析_python

Json是一种常用的数据交换结构,由于轻量、易于阅读和编写等特点,在网络方面应用很广。下面这篇文章主要介绍了Python对Json解析的相关资料,需要的朋友可以参考借鉴,下面来一起看看吧。

import json
 
data = {
 'name' : 'ACME',
 'shares' : 100,
 'price' : 542.23
}
 
json_str = json.dumps(data)
data = json.loads(json_str)
 
# Writing JSON data to file
with open('data.json', 'w') as f:
 json.dump(data, f)
 
# Reading data back
with open('data.json', 'r') as f:
 data = json.load(f) 
JSON Python object dict array list string unicode number (int) int, long number (real) float true True false False null None
>>> class JSONObject:
...  def __init__(self, d):
...   self.__dict__ = d
...
>>>
>>> data = json.loads(s, object_hook=JSONObject)
>>> data.name
'ACME'
>>> data.shares
50
>>> data.price
490.1 
def serialize_instance(obj):
 d = { '__classname__' : type(obj).__name__ }
 d.update(vars(obj))
 return d
 
# Dictionary mapping names to known classes
classes = {
 'Point' : Point
}
 
def unserialize_object(d):
 clsname = d.pop('__classname__', None)
 if clsname:
  cls = classes[clsname]
  obj = cls.__new__(cls) # Make instance without calling __init__
  for key, value in d.items():
   setattr(obj, key, value)
  return obj
 else:
  return d 
>>> p = Point(2,3)
>>> s = json.dumps(p, default=serialize_instance)
>>> s
'{"__classname__": "Point", "y": 3, "x": 2}'
>>> a = json.loads(s, object_hook=unserialize_object)
>>> a
<__main__.Point object at 0x1017577d0>
>>> a.x
2
>>> a.y
3 

以上就是深入理解Python对Json的解析_python的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于深入理解Python对Json的解析_python的详细内容...

  阅读:47次