简体   繁体   中英

Storing python dictionary in json file and substitute values upon reading

I am attempting to create a system that stores information about a sensor(s) in a json file. So far so good. I can store almost all the data in json and pull it out without issue.

Where I am stuck is with the database calls. This is a basic example of the json file for a fish tank sensor, but there are other that contain different sensor packages

{
    "sensor_info": {
        "name" : "fish tank",
        "unpack_commands" : "floatle:32, floatle:32"
    },

    "database_query" : "INSERT INTO fish_tank (pH, temperature, timestamp) VALUES ('%(pH)s', '%(temperature)s', TIMESTAMP(NOW(5)))",

    "database_data" : "{'pH': pH, 'temperature': temperature}"
}

Here is the fucntion that calls the data from the json. BTW I am using the bitstring library for this hence the unpack.

def fish_tank(sensor_info, data):

    unpack_commands = sensor_info['sensor_info']['unpack_commands']
    sql_statement = sensor_info['database_query']


    # Unpack the data from the incoming serial data
    pH, temperature = data.unpack(unpack_commands)    

    # Create the dictionary for database submission
    # data = sensor_info['database_data']
    data = {'pH': pH, 'temperature': temperature}

    Database().write_data(sql_statement, data) 

As you can see I store the dictionary of data in the json file, but I am not using it as I can't figure out how to pull in the dictionary from json and have the correct values inserted into the dictionary for writing to the database. The sql query works fine, the unpack works fine, all I need now is the data portion and I can create a generic sensor function (within reason).

Thanks

If data.unpack() returns a sequence , then don't use named parameters at all, just use the sequence:

{
    "sensor_info": {
        "name" : "fish tank",
        "unpack_commands" : "floatle:32, floatle:32"
    },

    "database_query" : "INSERT INTO fish_tank (pH, temperature, timestamp) VALUES (%s, %s, TIMESTAMP(NOW(5)))",
}

Now there are two positional SQL parameters, matching the sequence of two values returned from the data.unpack() call:

unpack_commands = sensor_info['sensor_info']['unpack_commands']
sql_statement = sensor_info['database_query']

# Unpack the data from the incoming serial data
params = data.unpack(unpack_commands)    

Database().write_data(sql_statement, params) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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