繁体   English   中英

如何使用python为json文件中的键添加值

[英]how to add value to key in json file using python

        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"]
        }
    ]
}

您不能附加新数据,它会破坏您的 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)

由于您想将项目附加到对象中的列表(而不是将文本附加到json文件本身),您需要先读取json ,然后附加并写入:

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)

好吧,您可以轻松添加它,而无需从旧 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)  

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

暂无
暂无

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

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