? ? ? ?Json 即?JavaScript Object Notation, 是一種常用的輕量級的文本數(shù)據(jù)交換格式, json數(shù)據(jù)格式簡單, 易于讀寫。
1、Json基本語法規(guī)則
? ? ? ? Json中有兩種常用的數(shù)據(jù)結(jié)構(gòu), 對象、數(shù)組。其中:
????????對象是由 "{}" 保存的無序的名稱/值對集合, 名稱與值之間用 ":", 名稱/值對之間用 "," 分隔,如? ? ?{ "name" : "school", "url" : "www.baidu.com" },
????????數(shù)組是由 "[]" 保存的值有序集合, 值與值之間用 "," 分隔,如[ "site1": "baidu", "site2" : "music", "www" ],
? ? ? ? json數(shù)組中的值可以是字符串(string)、數(shù)值(number)、true、false、 null、 對象(object)或者數(shù)組(array)以及它們的嵌套。
? ? ? ? json文件有以下幾點(diǎn)規(guī)范:
? ? ? ? 1) 數(shù)據(jù)保存在 "名稱/值" 的鍵值對中;
? ? ? ? 2)?數(shù)據(jù)之間用 "," 分隔, 數(shù)組或者對象(字典)的最后一個成員后不能加",";
? ? ? ? 3)?"\" 表示轉(zhuǎn)義字符,用 "{}" 表示對象,用 "[]" 表示數(shù)組。
2、Python中json文件的四種常用操作
? ? ? ? 1) json.dump() :?將Python對象序列化為json格式的數(shù)據(jù)流并寫入文件類型的對象中
import json
dic = {
"student" :
[
{"name" : "xlh",
"time" : "09:04"}
]
}
with open('./dic.json', mode='w', encoding='utf-8') as f:
json.dump(dic, f)
? ? ? ? 2) json.dumps() :?將Python對象序列化為json格式的字符串
import json
dic = {
"student" :
[
{"name" : "xlh",
"time" : "09:04"}
]
}
data = json.dumps(dic)
print("轉(zhuǎn)換為json前的數(shù)據(jù)類型為:\n{} \n轉(zhuǎn)換之后數(shù)據(jù)類型為: {}".format(type(dic), type(data)))
>>>
<class 'dict'>
<class 'str'>
? ? ? ? 3) json.load() : 從josn文件對象中讀取json格式的數(shù)據(jù)并反序列化成Python對象文章來源:http://www.zghlxwxcb.cn/news/detail-563585.html
import json
with open('./dic.json', encoding='utf-8') as f:
data = json.load(f)
print("讀取json文件數(shù)據(jù)為:\n{}\n數(shù)據(jù)類型為: {}".format(data, type(data)))
>>>
讀取json文件數(shù)據(jù)為:
{'student': [{'name': 'xlh', 'time': '09:04'}]}
數(shù)據(jù)類型為: <class 'dict'>
? ? ? ? 4) json.loads() 將包含json格式數(shù)據(jù)的字符串反序列化成Python對象文章來源地址http://www.zghlxwxcb.cn/news/detail-563585.html
import json
s = '{"name": "cdbe", "data": 10, "des": "json"}'
data = json.loads(s)
print("讀取json字符串:\n{}\n數(shù)據(jù)類型為: {}".format(data, type(data)))
>>>
讀取json字符串:
{'name': 'cdbe', 'data': 10, 'des': 'json'}
數(shù)據(jù)類型為: <class 'dict'>
到了這里,關(guān)于Python json文件常用操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!