如何使用python为json文件中的键添加值
我试图将值附加到键意图。但当我尝试附加值时,我得到的输出如下:如何使用python为json文件中的键添加值,python,json,file,Python,Json,File,我试图将值附加到键意图。但当我尝试附加值时,我得到的输出如下: data={} data['intents']=[] data['intents'].append({ 'tag': tag, 'patterns': patterns, 'response': response }) with open('training.json', 'a')
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"}]}
由于要将项目附加到对象中的列表中(而不是将文本附加到
json
文件本身),您需要首先读取json
,然后附加并写入:
{"intents":[
{"tag":"sale",
"patterns":["ptr1","ptr2"],
"responses":["resp1","resp2"]
},
{"tag":"purchase",
"patterns":["abc","def"],
"responses":["xyz","zzz"]
}
]
}
你不能附加新数据,因为它会破坏你的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',
'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)
这将在同一标记下追加新响应。另外,如果其中存在相同的响应,则它将跳过。您为什么关心密钥顺序?序列化语言不用于显示。实际上,我关心的不是意图。我需要将值附加到键缩进。但当我尝试这样做时,钥匙会重复。i、 e我在这里展示的东西。您能告诉我一种将键值对附加到单个键的方法吗@事实上,我关心的不是意图。我需要将值附加到键缩进。但当我尝试这样做时,钥匙会重复。i、 e我在这里展示的东西。你能告诉我一种将键值对附加到一个键上的方法吗
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)