我想制作一个程序来读取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
相关问题 更多 >
编程相关推荐