python 存儲json數(shù)據(jù)的操作
本篇我們將學(xué)習(xí)簡單的json數(shù)據(jù)的存儲
首先我們需要引入json模塊:import json
這里我們模擬一個常見常見,我們讓用戶輸入用戶名、密碼,在密碼輸入完成后提示用戶再次輸入密碼來確認(rèn)自己的輸入,如果兩次密碼一致,那么我們將用戶名和密碼以json格式寫入文件,否則提示用戶再次輸入密碼。
name = input('please enter your name:')password = input('please enter your password:')confirm_password = input('confirm your password:')while password != confirm_password: print('input password inconsistencies,please try again') password = input('please enter your password:') confirm_password = input('confirm your password:')
我們運(yùn)行下代碼確保我們的準(zhǔn)備工作沒有問題:
ok,我們可以通過用戶輸入拿到用戶名和密碼,接下來,我們就需要將兩者以json格式存入文件了。
首先,我們將我們的輸入轉(zhuǎn)化為json對象:
user_info = json.dumps({’username’: name, ’password’: password}, sort_keys=True, indent=4, ensure_ascii=False)print(user_info)
這里我們使用了json.dumps函數(shù),該函數(shù) 用于將 Python 對象編碼成 JSON 字符串。
語法:
def dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) Inferred type: (obj: Any, Any, skipkeys: bool, ensure_ascii: bool, check_circular: bool, allow_nan: bool, cls: Any, indent: Any, separators: Any, default: Any, sort_keys: bool, kw: Dict[str, Any]) -> str
其中sort_keys是用來指定在json格式的對象里面是否按照key的名稱來進(jìn)行排序,indent參數(shù)則指定縮進(jìn)的空格數(shù)目。
最后的輸入格式如下:
{ 'password': 'us', 'username': 'us'}
那么接下來我們就將這個json對象寫入到文件中去:
with open(’user_info.json’, ’w’, encoding=’utf-8’) as json_file: json.dump(user_info, json_file, ensure_ascii=False) print('write json file success!')
這里我們需要學(xué)習(xí)一個函數(shù)json.dump:
def dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw) Inferred type: (obj: Any, fp: {write}, Any, skipkeys: bool, ensure_ascii: bool, check_circular: bool, allow_nan: bool, cls: Any, indent: Any, separators: Any, default: Any, sort_keys: bool, kw: Dict[str, Any]) -> None
這個函數(shù)有兩個參數(shù)是我們必須要填寫的:obj(我們要存儲的數(shù)據(jù)), fp(文件句柄,也就是我們要存在那個文件里面)。
ensure_ascii=False這個參數(shù)是處理我們希望在json對象里面可以包含中文的場景
If ensure_ascii is false, then the strings written to fp can contain non-ASCII characters if they appear in strings contained in obj. Otherwise, all such characters are escaped in JSON strings.
如果不指定ensure_ascii=False,那么當(dāng)我們的數(shù)據(jù)里面包含中文的時候:
{'username': 'zhangu4e09', 'password': 'ddd'}
會有如上的顯示內(nèi)容。
我們運(yùn)行程序,依次輸入用戶名和密碼:
please enter your name:usplease enter your password:usconfirm your password:us{'username': 'us', 'password': 'us'}write json file success!Process finished with exit code 0
然后我們看下文本文件中的內(nèi)容:
接下來我們就需要學(xué)習(xí)一下怎么讀取json格式的內(nèi)容了。
with open(’user_info.json’, ’r’, encoding=’utf-8’) as json_file: data = json.load(json_file) print(data)
讀取json數(shù)據(jù)需要使用json.load函數(shù):
def load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw) Inferred type: (fp: {read}, Any, cls: Any, object_hook: Any, parse_float: Any, parse_int: Any, parse_constant: Any, object_pairs_hook: Any, kw: Dict[str, Any]) -> Any
這里我們需要提供一個參數(shù)fp,也就是我們要操作的文件句柄。
程序運(yùn)行輸出:
{'username': 'us', 'password': 'us'}
我們可以打印一下json.load返回的是什么類型的:
print(type(data))
輸出:
<class ’str’>
可見,這是一個字符串,這是為什么呢?難道不應(yīng)該返回的是python對應(yīng)的對象嗎?
在上面的代碼中我們在寫入文件前面調(diào)用過:
user_info = json.dumps({’username’: name, ’password’: password}, ensure_ascii=False)
這一行代碼,大家還記得吧,它返回的是一個json字符串,所以上面的例子中我們需要使用json.loads重新反序列化為python對象,這一點(diǎn)大家留意一下,上面的例子我們是為了給大家演示json.loads的相關(guān)用法,使用如下:
data = json.loads(data)print(type(data))print(data[’username’])
如果沒有這行代碼,那么 data = json.load(json_file)返回的就是我們自己組織的數(shù)據(jù)結(jié)構(gòu)了,如果還是{‘username’: name, ‘password’: password}這種格式,那么返回就是一個字典對象。
下面我們在通過一個list來看一下:
data = [1,2,3,4,5]with open(’user_info.json’, ’w’, encoding=’utf-8’) as json_file: json.dump(data, json_file, ensure_ascii=False)with open(’user_info.json’, ’r’, encoding=’utf-8’) as json_file: data = json.load(json_file) print(type(data)) print(data)
運(yùn)行程序:
<class ’list’>
[1, 2, 3, 4, 5]
補(bǔ)充:Python創(chuàng)建并保存json文件,支持?jǐn)?shù)據(jù)更新保存
大家還是直接看代碼吧~import jsonclass Params(): '''Class that loads hyperparameters from a json file.Example:```params = Params(json_path)print(params.learning_rate)params.learning_rate = 0.5 # change the value of learning_rate in params```''' def __init__(self, json_path):with open(json_path) as f: params = json.load(f) # 將json格式數(shù)據(jù)轉(zhuǎn)換為字典 self.__dict__.update(params) def save(self, json_path):with open(json_path, ’w’) as f: json.dump(self.__dict__, f, indent=4) # indent縮進(jìn)級別進(jìn)行漂亮打印 def update(self, json_path):'''Loads parameters from json file'''with open(json_path) as f: params = json.load(f) self.__dict__.update(params) @property # Python內(nèi)置的@property裝飾器就是負(fù)責(zé)把一個方法變成屬性調(diào)用的 def dict(self):'''Gives dict-like access to Params instance by `params.dict[’learning_rate’]'''return self.__dict__if __name__ == ’__main__’: parameters = {'SEED': 1, 'dataset': 'Omniglot', 'meta_lr': 1e-3, 'num_episodes': 5000, 'num_classes': 5, 'num_samples': 1, 'num_query': 10, 'num_steps': 100, 'num_inner_tasks': 8, 'num_train_updates': 1, 'num_eval_updates': 1, 'save_summary_steps': 100, 'num_workers': 1 } json_str = json.dumps(parameters, indent=4) with open(’params.json’, ’w’) as f: # 創(chuàng)建一個params.json文件f.write(json_str) # 將json_str寫到文件中 params = Params(’params.json’) params.SEED = 2 # 修改json中的數(shù)據(jù) params.save(’params.json’) # 將修改后的數(shù)據(jù)保存
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
