【问题标题】:How to append key values to JSON file properly (without creating extra structure)?如何正确地将键值附加到 JSON 文件(不创建额外的结构)?
【发布时间】:2019-06-20 19:53:19
【问题描述】:

我想在 Python 中创建存储 X 和 Y 值的 JSON 文件。它应该看起来像这样:

{"X": [[1,2,3], [2,3,5], [1,2,6], [1,2,3], [2,3,5], [1,2,6]],"Y": [3,5,1,3,5,1]}

这是我写的代码,首先我检查文件是否为空(如果是,则在 json 文件中创建 X 和 Y)。

  def save_data(x, y):
        data_from_json = {}
        with open('data_sets.json', 'r+') as json_file:
            if (os.stat('data_sets.json').st_size == 0):
                if "X" not in data_from_json:
                    data_from_json.setdefault('X', x)
                if "Y" not in data_from_json:
                    data_from_json.setdefault('Y', y)
                json.dump(data_from_json, json_file)
        with open('data_sets.json', 'r+') as json_file:
            data_from_json = json.load(json_file)
            data_from_json['X'].append(x)
            data_from_json['Y'].append(y)
            json.dump(data_from_json, json_file)

我得到的是这样的:

{"X": [[1,2,3], [2,3,5], [1,2,6]],"Y": [3,5,1]}{"X": [[1,2,3], [2,3,5], [1,2,6]],"Y": [3,5,1]} 

而不是用新值附加 X 和 Y。我该怎么办?

【问题讨论】:

  • 第一个 with 块中的 if 测试似乎没有必要。 data_from_json 是空的,因为你刚刚创建了它,所以测试显然会成功。您的意思是先从文件中读取吗?
  • 当您使用 json.load() 时,您正在读取您刚刚编写的相同 JSON。那有什么意义呢?

标签: python arrays json


【解决方案1】:

当文件为空时,您将向其写入两次 JSON。您编写一个初始字典,然后再次读取该文件并附加到 XY 列表。

将代码路径分成两部分更简单:一部分用于创建初始文件,另一部分用于附加到现有文件。

另外,如果你使用同一个文件打开方式来读写文件,你需要在它们之间调用seek()来回退到文件的开头。否则,您将在原始 JSON 之后编写更新的 JSON。

def save_data(x, y):
    if (os.stat('data_sets.json').st_size == 0):
        # File is empty, create initial dictionary
        data_from_json = {"X": [x], "Y", [y]}
        with open('data_sets.json', 'w') as json_file:
            json.dump(data_from_json, json_file)
    else:
        with open('data_sets.json', 'r+') as json_file:
            data_from_json = json.load(json_file)
            data_from_json.setdefault('X', [])
            data_from_json.setdefault('Y', [])
            data_from_json['X'].append(x)
            data_from_json['Y'].append(y)
            json_file.seek(0)
            json.dump(data_from_json, json_file)

【讨论】:

    猜你喜欢
    • 2016-12-11
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 2017-04-03
    • 1970-01-01
    • 2013-10-15
    • 2019-11-25
    • 1970-01-01
    相关资源
    最近更新 更多