python 讀寫json檔案

2021-09-27 07:03:53 字數 1792 閱讀 7877

以字串的形式進行json讀寫

函式功能

json_str = json.dumps(要寫入的字典表)

將字典表寫入json字串

json_data = json.loads(json_str)

將json字串讀為字典表

import json

"""json的true,false,null寫法和字典表(true,false,none)不一樣"

""def json_basic()

: data =

print

(data)

print

('-'*20

) # 把字典表寫入json字串,dump的s代表弄在字串裡面

json_str = json.

dumps

(data)

print

(json_str)

# 把json字串讀為python的字典表

json_data = json.

loads

(json_str)

print

('-'*20

)print

(json_data)

if __name__ ==

'__main__'

:json_basic()

----

----

----

----

----

----

----

----

----

----

函式

功能json.dump(data, f)

data為字典表,將data寫入到json檔案(f)

data = json.load(f)

從json檔案中讀取資料

def json_writer_file()

:"""寫json文件(json文件可以用作網頁上的api介面資料)"

""with

open

('data.json'

,'w'

, encoding=

'utf-8'

)as f:

data =

json.

dump

(data, f)

def json_read_file()

:"""讀取json檔案"

""with

open

('data.json'

,'r'

, encoding=

'utf-8'

)as f:

data = json.

load

(f)print

(data)

if __name__ ==

'__main__'

:json_writer_file()

json_read_file()

json的語法大致和python的字典表一樣,都是鍵值對,但true,false,null寫法和字典表(true,false,none)不一樣。

def json_type_diff()

:"""型別差異"

"" data =

print

(json.

dumps

(data)

)if __name__ ==

'__main__'

:json_type_diff()

python讀寫Json檔案記錄

在這裡記錄一下自己讀寫json檔案的問題 讀取多行的json檔案 直接讀取會出錯,可以逐行讀取 datas open file,r encoding utf 8 readlines for line in datas data json.loads line 寫入json檔案,主要是解決中文亂碼的問...

python 讀寫txt檔案 json檔案

首先第一步,開啟檔案,有兩個函式可供選擇 open 和 file f open file.txt w file.close f file file.json r file.close 記得開啟檔案時最後不要忘記關閉!open 和 file 都是python的內建函式,返回乙個檔案物件,具有相同的功能...

json讀寫檔案

jsonc 寫配置檔案比較簡單,並且解析配置檔案也比較省事。寫配置檔案 cpp view plain copy include include include include include inc json.h define config file config.json typedef stru...