程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Detailed explanation of Python Foundation (15):json dump()、json. dumps()、json. load()、json. loads()

編輯:Python

Python Basic explanation

  • One . The usage function
  • Two . Execute code
    • 2.1 json.dumps()
    • 2.2 json.dump()
    • 2.3 json.loads()
    • 2.4 json.load()

One . The usage function

  • json.dumps(): take Python The data structure is converted to JSON, namely dict Type into str type .
  • json.dump(): code , Is used to dict Type of data into str type , And written to the json file .
  • json.loads(): take JSON The encoded string is converted back to Python data structure , namely str Type conversion to dict type .
  • json.load(): decode , For from json The data is read from the file .

Two . Execute code

2.1 json.dumps()

Sometimes the saved Chinese data turns into ASCII code , It is necessary to put ensure_ascii Parameter set to False

import json
data = {

'name' : 'name',
'age' : 20,
}
json_str = json.dumps(data,ensure_ascii=False)
main parameter effect type obj Is that you have to transform into json The object of sort_keys Encoders are sorted by dictionary (a To z) Output Boolindent Indent the display according to the data format Intseparators Set separator strskipkeys Check python Basic type Boolensure_ascii Output Yes No ASCLL code Boolcheck_circular Circular reference checking for container types Bool

2.2 json.dump()

import json
data = {

'name':'name',
'age':20,
}
# speak python Code as json Put it in that file 
filename = 'a.txt'
with open (filename,'w') as f:
json.dump(data ,f)

2.3 json.loads()

import json
# use dumps take python Code as json character string 
data = json.dumps(data)
# use loads take json Code as python
print(json.loads(data))

2.4 json.load()

import json
data = {

'name':'name',
'age':20
}
filename = 'a.txt'
with open (filename,'w') as f:
json.dump(data,f)
with open (filename) as f_:
print(json.load(f_))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved