简体   繁体   English

python:从文件中读取json数据并追加更多数据

[英]python: read json data from file and append more data

I'm trying to read existing data from a json file and trying to append more data to the file using python (I'm a python newbie). 我正在尝试从json文件中读取现有数据,并尝试使用python(我是python新手)将更多数据附加到文件中。 Here is my existing data in data.json file which I read in my script: 这是我在脚本中读取的data.json文件中的现有数据:

{
    "Config1": {
        "TestCase1": {
            "Data1": 200,
            "Data2": 2715
        }
    },
    "Config2": {
        "TestCase1": {
            "Data1": 2710,
            "Data2": 2715
        }
    }
}

After reading I want to append TestCase2 data. 阅读后,我想附加TestCase2数据。 This is what I'm doing: 这就是我在做什么:

with open("data.json") as json_file: #load existing data
    json_data = json.load(json_file)

test='TestCase2'
result=json_data
myConfigs = ['Config1','Config2']
for each, config in enumerate(myConfigs):
    result.update({config:{test:{'Data1':2600,'Data2':2900}}})
with open('data.json', 'a') as outfile:
    json.dump(result, outfile)

The new data in data.json is not valid as pointed by jsonLint . 正如jsonLint指出的那样 ,data.json中的新数据无效。 What am I doing wrong? 我究竟做错了什么? Here is the new data 这是新数据

{
        "Config1": {
            "TestCase1": {
                "Data1": 200,
                "Data2": 2715
            }
        },
        "Config2": {
            "TestCase1": {
                "Data1": 2710,
                "Data2": 2715
            }
        }
    } {
        "Config1": {
            "TestCase2": {
                "Data1": 2600,
                "Data2": 2900
            }
        },
        "Config2": {
            "TestCase2": {
                "Data1": 2600,
                "Data2": 2900
            }
        }
    }

The problem is that you're appending the new JSON to the original JSON file here: 问题是您要在此处将新的JSON附加到原始JSON文件中:

with open('data.json', 'a') as outfile:
    json.dump(result, outfile)

So you have two JSON objects in the same file as you can see: 因此,您可以在同一文件中看到两个JSON对象:

...
            "Data2": 2715
        }
    }
} {  <--- original object ends here, new object starts here
    "Config1": {
...

JSONLint is expecting a single object, as will any JSON parser. JSONLint和任何JSON解析器都期望有一个对象。

In addition to opening the file in the wrong mode (should be 'w'), you are also overwriting your old "config" trees by defining a new dict inline. 除了以错误的模式(应为“ w”)打开文件之外,您还通过定义新的dict内联覆盖了旧的“ config”树。

Instead of: 代替:

result.update({config:{test:{'Data1':2600,'Data2':2900}}})

Try this: 尝试这个:

result[config][test] = {'Data1': 2600, 'Data2': 2900}

This should give you the result you are looking for with your example. 这样可以为您的示例提供所需的结果。 It will let result['Config1']['TestCase1'] persist while you add TestCase2. 添加TestCase2时,它将使result['Config1']['TestCase1']保持result['Config1']['TestCase1'] You may also need to make sure that the config tree exists by setting result[config] to {} if it's None . 您可能还需要通过将result[config]设置为{}如果它为None来确保配置树存在。

The main problem is that the dict1.update(dict2) method overwrites dict1 keys if the same exist in dict2 hence the second object in your file doesn't have key => TestCase1 主要问题是,如果dict2存在dict1.update(dict2)方法, dict1覆盖dict1键,因此文件中的第二个对象没有key => TestCase1

Another problem is that (as pointed above) the file is opened in the wrong mode (Should be w ) as a appends to the json file 另一个问题是(如上所述)该文件以错误的方式打开(应该为w ),作为对json文件a追加

You could try this: 您可以尝试以下方法:

with open("data.json") as json_file:
    json_data = json.load(json_file)

test='TestCase2'
result=json_data
myConfigs = ['Config1','Config2']
for each, config in enumerate(myConfigs):
    result[config].update({test:{'Data1':2600,'Data2':2900}})
with open('data.json', 'w') as outfile:
    json.dump(result, outfile)

Just result[config].update(... instead of result.update({config:... 只是result[config].update(...而不是result.update({config:...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM