T
T
tteqwe2019-08-12 12:26:16
Python
tteqwe, 2019-08-12 12:26:16

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)

As a result, this is what is obtained in json.
{
    "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"
    }
}

Maybe someone faced a similar problem. Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly Lazarev, 2019-08-12
@tteqwe

Well, quite logical behavior, given that you do not separate the record in any way, but stupidly write post_dataas 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 question

Ask a Question

731 491 924 answers to any question