code:
import json
import os
dirname = r"D:\json"
basename = "test_json_comment.json"
fpath = os.path.join(dirname, basename)
with open( fpath , encoding="UTF-8" ) as json_file:
dic = json.load(json_file)
json_file.seek(0,0)
strr = json_file.read()
print("strr:",strr)
dic1 = json.loads(strr)
print("\ndic:",dic)
print("\ndic1",dic1)輸出結果:

json.load 方法用於從文件中讀取並解析JSON數據,然後將其轉換為Python數據結構(字典、列表等)。在代碼中,已經使用了 json.load 來加載數據,並將其存儲在了 dic 變量中,因此不需要再次使用 json_file.read() 來讀取JSON文件的內容。
一旦使用 json.load 方法讀取了JSON文件的內容,文件指針就會在文件的末尾,若沒有json_file.seek(0,0)跳回文件的一開頭,再次調用 json_file.read() 將返回空字符串,因為已經到達了文件的末尾。
json.load(json_file) 跟
json.loads(strr)
參數的型別不一樣:

json_file.seek(0,0)
#第一個0表示文件之開頭
#第二個0表示偏移0

推薦hahow線上學習python: https://igrape.net/30afN




![Python: 字串 str.find(關鍵字[,start][,end]),找不到的話回傳-1,如何找出資料字串中,所有關鍵字的index?詞頻計算 Python: 字串 str.find(關鍵字[,start][,end]),找不到的話回傳-1,如何找出資料字串中,所有關鍵字的index?詞頻計算](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2022/11/20221122100657_32.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python: matplotlib如何設定座標軸刻度? plt.xticks(seq, labels) ;如何生成fig, ax物件? fig = plt.figure(figsize= (10.24, 7.68)) ; ax = fig.add_subplot() ; fig, ax = plt.subplots(figsize=(10.24, 7.68)) ; 如何使用中文? plt.rcParams[“font.family”] = [“Microsoft JhengHei”] Python: matplotlib如何設定座標軸刻度? plt.xticks(seq, labels) ;如何生成fig, ax物件? fig = plt.figure(figsize= (10.24, 7.68)) ; ax = fig.add_subplot() ; fig, ax = plt.subplots(figsize=(10.24, 7.68)) ; 如何使用中文? plt.rcParams[“font.family”] = [“Microsoft JhengHei”]](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2023/02/20230209083006_41.png?quality=90&zoom=2&ssl=1&resize=350%2C233)
![Python: pandas.read_excel(r”路徑\檔名.副檔名”, header = None), 自動加上0,1…的欄標籤, DataFrame如何取某一直欄或橫列? 如何用 .iloc[bool_list] 取出判斷式為真的那一列? bool_list = list( df[0] == 0 ) ; bool_list = list(df[0].isin([0])) ; DataFrame如何顯示完整的資料? pandas.set_option ( “display.max_rows”, None) Python: pandas.read_excel(r”路徑\檔名.副檔名”, header = None), 自動加上0,1…的欄標籤, DataFrame如何取某一直欄或橫列? 如何用 .iloc[bool_list] 取出判斷式為真的那一列? bool_list = list( df[0] == 0 ) ; bool_list = list(df[0].isin([0])) ; DataFrame如何顯示完整的資料? pandas.set_option ( “display.max_rows”, None)](https://i0.wp.com/savingking.com.tw/wp-content/uploads/2022/11/20221128164005_44.png?quality=90&zoom=2&ssl=1&resize=350%2C233)



近期留言