Sequencing module json

json module 
json is a common data transmission format, essentially a string

json required { 'key': value}
  • key must be a string, value can only be: dictionaries, lists, strings, numbers, bool value
  • In any language of his type must be of type string
  • json is that all languages ​​have become recognized as a data type
  • If the language is python java language to give information to send, it can be converted into json format. java conversion can be obtained through a series of data types

json serialization (dump / dumps) and deserialize (load / loads)

JSON Import 

DIC = { 'Beijing': { 'fengtai': {}, 'Haidian ": {}}}
Print (DIC)
dic_str = json.dumps (DIC, ensure_ascii = False) # serialization process, the dictionary / Other data type is converted into a string,
  ensure_ascii = False, if there are Chinese dictionary, you want to write the data also showed that Chinese, it is necessary to add parameters

print(dic_str)

with open('file',mode='w',encoding='utf-8') as f:
f.write(dic_str)
import json

lst = [1,2,3,4,56]
with open('file',mode='w',encoding='utf-8') as f:
    json.dump(lst,f)

with open('file',mode='r',encoding='utf-8') as f1:
    ret = json.load(f1)
    print(ret)

 

loads dumps and interactive memory

load dump and file interaction

 

import pickle

pickle module 
1. python language-specific sequencing module
Import the pickle 
DIC = { ' Beijing ' : { ' sun ' : ' Changping ' }, ( ' Tianjin ' , ' Hebei ' ): [l, 2,3 ]} 
RET = the pickle.dumps (DIC)
 Print (RET) 

str_d = The pickle.loads (RET)
 Print (str_d) 


Import the pickle 

DIC = { ' Beijing ' : { ' sun ' : ' Changping ' }, ( '天津','河北'):[1,2,3]}
with open('file',mode='wb') as f:
    pickle.dump(dic,f)

with open('file',mode='rb') as f1:
    ret = pickle.load(f1)
    print(ret)

 

The difference between the pickle and json 

1.pickle supports almost all data types in python, but only a python language used
2.json supports all languages, but only limited data type support

 

Guess you like

Origin www.cnblogs.com/lxc123/p/12339772.html