[英]Reading and writing a json file in python
我想制作一個讀取 json 文件的程序,如果它不存在,則使用一些默認參數創建該文件。 我遇到的問題是以下代碼不起作用。
import json
file_json = '/home/sga/Documents/Python/dracula.json'
font = ''
with open(file_json) as file:
data = json.loads(file.read())
if 'font' in data:
font = data['font']
else:
with open(file_json, 'w') as file_data:
data['font'] = 'UbuntuMono'
data_encoded = json.dump(data)
file.write(data_encoded)
當我運行它時,我收到以下錯誤:
Traceback (most recent call last):
File "/home/sga/Documents/Python/Proof/font.py", line 6, in <module>
data = json.loads(file.read())
File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.9/json/decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
我擁有的 json 文件如下:
{
"dark": [
"#292d3e",
"#292d3e"
],
"grey": [
"#434758",
"#434758"
],
"light": [
"#ffffff",
"#ffffff"
],
"text": [
"#292d3e",
"#292d3e"
],
"focus": [
"#A77AC4",
"#A77AC4"
],
"urgent": [
"#ff5555",
"#ff5555"
],
"active": [
"#f1ffff",
"#f1ffff"
],
"inactive": [
"#4c566a",
"#4c566a"
],
"color1": [
"#ff5555",
"#ff5555"
],
"color2": [
"#A77AC4",
"#A77AC4"
],
"color3": [
"#7197E7",
"#7197E7"
],
"color4": [
"#ffb86c",
"#ffb86c"
]
}
執行后我想要的結果如下:
{
"dark": [
"#292d3e",
"#292d3e"
],
"grey": [
"#434758",
"#434758"
],
...
"font" : "UbuntuMono"
}
做了一些編輯,但這就是你想要的。 請注意何時使用 json.load/loads 和 json.dump/dumps。
font = ''
data = json.load(open(file_json)) # load for file, not loads
if 'font' in data:
print('Yes font')
font = data['font']
else:
with open(file_json, 'w') as file_data:
data['font'] = 'UbuntuMono'
data_encoded = json.dumps(data) # dumps, not dump
file_data.write(data_encoded)
所以我假設你在追求這樣的事情。 這只是一些快速代碼,可以為您指明正確的方向。
import json
import os
file_json = 'dracula.json'
font = ''
# Not sure if in your case you need this but if the file does not exist then create it.
if not os.path.exists(file_json):
with open(file_json, "w") as fw:
json.dump({"font": "UbuntuMono"}, fw, indent=2)
# if the file exists then read it.
with open(file_json, "r") as fr:
data = json.load(fr)
# this is where we check to see if the key you have asked for is present.
if 'font' in data:
font = data['font']
print(f"Found font {font}")
# if we didnt find the key then back fill the value into the data
else:
with open(file_json, "w") as fw:
data['font'] = 'UbuntuMono'
json.dump(data, fw, indent=2)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.