python 存儲(chǔ)json數(shù)據(jù)的操作
本篇我們將學(xué)習(xí)簡(jiǎn)單的json數(shù)據(jù)的存儲(chǔ)
首先我們需要引入json模塊:
import json
這里我們模擬一個(gè)常見常見,我們讓用戶輸入用戶名、密碼,在密碼輸入完成后提示用戶再次輸入密碼來確認(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對(duì)象:
user_info = json.dumps({'username': name, 'password': password}, sort_keys=True, indent=4, ensure_ascii=False) print(user_info)
這里我們使用了json.dumps函數(shù),該函數(shù) 用于將 Python 對(duì)象編碼成 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格式的對(duì)象里面是否按照key的名稱來進(jìn)行排序,indent參數(shù)則指定縮進(jìn)的空格數(shù)目。
最后的輸入格式如下:
{ "password": "us", "username": "us" }
那么接下來我們就將這個(gè)json對(duì)象寫入到文件中去:
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í)一個(gè)函數(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
這個(gè)函數(shù)有兩個(gè)參數(shù)是我們必須要填寫的:obj(我們要存儲(chǔ)的數(shù)據(jù)), fp(文件句柄,也就是我們要存在那個(gè)文件里面)。
ensure_ascii=False這個(gè)參數(shù)是處理我們希望在json對(duì)象里面可以包含中文的場(chǎng)景
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ù)里面包含中文的時(shí)候:
{"username": "zhang\u4e09", "password": "ddd"}
會(huì)有如上的顯示內(nèi)容。
我們運(yùn)行程序,依次輸入用戶名和密碼:
please enter your name:us please enter your password:us confirm 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
這里我們需要提供一個(gè)參數(shù)fp,也就是我們要操作的文件句柄。
程序運(yùn)行輸出:
{"username": "us", "password": "us"}
我們可以打印一下json.load返回的是什么類型的:
print(type(data))
輸出:
<class 'str'>
可見,這是一個(gè)字符串,這是為什么呢?難道不應(yīng)該返回的是python對(duì)應(yīng)的對(duì)象嗎?
在上面的代碼中我們?cè)趯懭胛募懊嬲{(diào)用過:
user_info = json.dumps({'username': name, 'password': password}, ensure_ascii=False)
這一行代碼,大家還記得吧,它返回的是一個(gè)json字符串,所以上面的例子中我們需要使用json.loads重新反序列化為python對(duì)象,這一點(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}這種格式,那么返回就是一個(gè)字典對(duì)象。
下面我們?cè)谕ㄟ^一個(gè)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 json class 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í)別進(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é)把一個(gè)方法變成屬性調(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)建一個(gè)params.json文件 f.write(json_str) # 將json_str寫到文件中 params = Params('params.json') params.SEED = 2 # 修改json中的數(shù)據(jù) params.save('params.json') # 將修改后的數(shù)據(jù)保存
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
python進(jìn)度條顯示-tqmd模塊的實(shí)現(xiàn)示例
這篇文章主要介紹了python進(jìn)度條顯示-tqmd模塊的實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-08-08pycharm設(shè)置虛擬環(huán)境與更換鏡像教程
這篇文章主要介紹了pycharm設(shè)置虛擬環(huán)境與更換鏡像教程,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-09-09Python實(shí)現(xiàn)像awk一樣分割字符串
這篇文章主要介紹了Python實(shí)現(xiàn)像awk一樣分割字符串,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09citespace數(shù)據(jù)處理:用python對(duì)Ref文檔進(jìn)行去重方式
這篇文章主要介紹了citespace數(shù)據(jù)處理:用python對(duì)Ref文檔進(jìn)行去重方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11pytorch中交叉熵?fù)p失函數(shù)的使用小細(xì)節(jié)
這篇文章主要介紹了pytorch中交叉熵?fù)p失函數(shù)的使用細(xì)節(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02Python 使用SMOTE解決數(shù)據(jù)不平衡問題(最新推薦)
SMOTE是一種強(qiáng)大的過采樣技術(shù),可以有效地處理不平衡數(shù)據(jù)集,提升分類器的性能,通過imbalanced-learn庫(kù)中的SMOTE實(shí)現(xiàn),我們可以輕松地對(duì)少數(shù)類樣本進(jìn)行過采樣,平衡數(shù)據(jù)集,這篇文章主要介紹了Python 使用SMOTE解決數(shù)據(jù)不平衡問題,需要的朋友可以參考下2024-05-05Python Pandas Dataframe.describe()使用及代碼實(shí)例
這篇文章主要介紹了Python Pandas Dataframe.describe()使用及代碼實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09Python中反轉(zhuǎn)二維數(shù)組的行和列問題
這篇文章主要介紹了Python中反轉(zhuǎn)二維數(shù)組的行和列問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01