小記憶之json 序列化

字典定義:dict是python中一種經常使用的數據類型,以關鍵字爲索引,關鍵字能夠是任意不可變類型,一般用字符串或數值,若是元組中只包含字符串和數字,它能夠做爲關鍵字,理解字典的最佳方式是把它看做無需的鍵值對(key:value)集合,鍵必須是惟一的。
json (JavaScrtpt Object Notation):由RFC 7159(which obsoletesRFC 4627) 和ECMA-404指定,是一個受JavaScript的對象字面量語法啓發的輕量級數據交換格式。
dict 轉json 字符串:
dumps:將_obj_序列化爲JSON格式的[`str`]。
import json
test_dict = {'name': 'tfz', 'age': 18, 'sex': 'male'}  

dict_to_json_str = json.dumps(test_dict)  
print(dict_to_json_str) 
#  {"name": "tfz", "age": 18, "sex": "male"}
print(type(dict_to_json_str))
#  <class 'str'>
序列化obj爲一個JSON格式的流並輸出到fp
import json  

test_dict = {'name': 'tfz', 'age': 18, 'sex': 'male', '中文': '值'}  

with open("./tfz.json", mode="w", encoding='utf-8') as f:  
   json.dump(test_dict, f, ensure_ascii=False)

15.png

讀取一個json文件並轉化爲一個json對象
"""將fp(一個支持`.read()`幷包含一個JSON文檔的[text file]或者[binary file] 反序列化爲一個 Python 對象。"""

import json  
with open('./tfz.json', mode='r', encoding='utf-8') as fp:  
   json_obj = json.load(fp)  
   print(json_obj)  
   print(type(json_obj))

16.png

序列化 s (a[str],[bytes])or[bytearray]instance containing aJSONdocument) 爲python對象
import json  

test_dict = [{'name': 'tfz', 'age': 18, 'sex': 'male', '中文': '值'}]  
json_str = json.dumps(test_dict, ensure_ascii=False)  
js = json.loads(json_str, encoding='utf-8')  
print(js)  
print(type(js))
# 序列化一個實例對象
import json  


class Computer(object):  

   def __init__(self, name, price):  
      self.name = name  
      self.price = price  


def serialize_instance(obj):  
   d = {'__class_name__': type(obj).__name__}  
   d.update(vars(obj))  
   return d  


computer = Computer("tfz", 10086)  

c = json.dumps(computer, default=serialize_instance)  
print(c)

17.png

獲取序列化後的實例對象
classes = {  
   "Computer": Computer  
}  


def unserialize_instance(d):  
   cls_name = d.pop('__class_name__', None)  
   if cls_name:  
      _cls = classes[cls_name]  
      # make instance without calling __init__  
  obj = _cls.__new__(_cls)  
      for key, value in d.items():  
         setattr(obj, key, value)  
      return obj  
   else:  
      return d  


unserialize_c = json.loads(c, object_hook=unserialize_instance)  
print(unserialize_c)  
print(type(unserialize_c))

18.png

相關文章
相關標籤/搜索