如何使用python向json文件中的密钥添加值

时间:2018-11-22 05:38:48

标签: python json file

        data={}
        data['intents']=[]
        data['intents'].append({
            'tag': tag,
            'patterns': patterns,
            'response': response
        })
        with open('training.json', 'a') as training:

            json.dump(data, training)

我正在尝试将值附加到关键意图上。但是当我尝试附加值时,我得到的输出如下:

{"intents": [{"response": "customize", "patterns": "erp", "tag": "purchase"}]}{"intents": [{"response": "kjj", "tag": "sales", "patterns": "jjkj"}]}

我希望我的输出格式如下:

{"intents":[
        {"tag":"sale",
         "patterns":["ptr1","ptr2"],
         "responses":["resp1","resp2"]
        },
        {"tag":"purchase",
         "patterns":["abc","def"],
         "responses":["xyz","zzz"]
        }
    ]
}

3 个答案:

答案 0 :(得分:1)

您无法添加新数据,否则它将破坏json,因此必须替换数据。而且不要专注于缩进,这是没有必要的 试试这个:

import json
data={}
data['intents']=[]
data['intents'].append({
    'tag': 'tag',
    'patterns': 'patterns',
    'response': 'response'
})
try:
    with open('training.json', 'r') as training:
        old_data = training.readlines()
        if old_data:
            old_data = json.loads(old_data[0])
            for intents in data['intents']:
                old_data['intents'].append(intents)
            data = old_data
            old_data = None
    with open('training.json', 'w') as training:
        json.dump(data, training)
except:
    with open('training.json', 'w') as training:
        json.dump(data, training)

答案 1 :(得分:0)

由于要将项目追加到对象的列表中(而不是将文本追加到json文件本身),需要首先读取json,然后追加并编写:< / p>

import os

data = {'intents': []}
if os.path.exists('training.json'):
    with open('training.json', 'r') as f:
        data = json.load(f)

data['intents'].append({
            'tag': tag,
            'patterns': patterns,
            'response': response
})

with open('training.json', 'w') as training:
    json.dump(data, training)

答案 2 :(得分:0)

您可以添加它而无需轻松复制旧JSOF文件中的内容。

    import json

    data={}
    data['intents']=[]
    data['intents'].append({
        'tag': 'tag',
        'patterns': 'patterns',
        'responses': 'responses'
    })

    tag = request.json['tag']
    new_response = request.json['response']
    for intent in intents['intents']:
        if intent['tag'] in tag:
            if new_response in intent['responses']:
                response = {"success":False,"message":"Response already found in the training data"}
                return response
            else:
                
                print("updating file")
                intent['responses'].append(new_response)
                data = intents
                with open('intents.json', 'w') as training:
                    json.dump(data, training)  

这会将新的响应附加在同一标签下。另外,如果其中存在相同的响应,则它将跳过。