用python读写json文件

2024-09-29 21:45:03 发布

您现在位置: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"
}

Tags: 文件inpyjsondatausrlinefile
2条回答

我想你是在追求这样的东西。这只是一些快速的代码,为您指出正确的方向

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)

进行了一些编辑,但这符合您的要求。注意何时使用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)

相关问题 更多 >

    热门问题