Answer the question
In order to leave comments, you need to log in
Write to json file and update python?
Hello. The user on the client selects the TCP or COM connection type. Fills in the fields and sends to the server. On the server, I'm trying to save data to a json file. But something does not work out to separate the data, if TCP, then write to TCP, if COM, then to COM. well, when updating information, update this json.
if request.method == 'POST':
post_data = request.get_json()
to_json = {'COM-port':post_data, 'TCP':post_data}
with open('sw_templates.json', 'w', encoding='utf-8') as f:
json.dump(to_json, f, sort_keys=False, indent=4, separators=(',', ': '), ensure_ascii=False)
{
"COM-port": {
"type": "com",
"ports": "com1",
"speed": "115200",
"bit": "8",
"parity": "Нет",
"stream": "Нет",
"stop_bit": "Один",
"timeout": "1000"
},
"TCP": {
"type": "com",
"ports": "com1",
"speed": "115200",
"bit": "8",
"parity": "Нет",
"stream": "Нет",
"stop_bit": "Один",
"timeout": "1000"
}
}
Answer the question
In order to leave comments, you need to log in
Well, quite logical behavior, given that you do not separate the record in any way, but stupidly write post_data
as a value both in the key 'COM-port'
and in the key 'TCP'
.
In order to split the entry, you should check the value , and depending on what is there, write it as the value of the corresponding key in the final config.
Something ala:post_data['type']
post_data = request.get_json()
if post_data['type'] == 'com':
to_json = {'COM-port': post_data}
elif post_data['type'] == 'tcp':
to_json = {'TCP': post_data}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question