[英]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. 我试图创建一个在json文件中存储有关传感器信息的系统。 So far so good.
到现在为止还挺好。 I can store almost all the data in json and pull it out without issue.
我可以将几乎所有数据存储在json中,并将其毫无问题地拉出。
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
这是鱼缸传感器的json文件的基本示例,但是还有其他包含不同传感器包的示例
{
"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. 这是从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. 如您所见,我将数据字典存储在json文件中,但是我没有使用它,因为我不知道如何从json中提取字典并将正确的值插入字典中以写入数据库。 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).
sql查询工作正常,unpack工作正常,我现在需要的只是数据部分,我可以创建一个通用的传感器函数(在一定程度上)。
Thanks 谢谢
If data.unpack()
returns a sequence , then don't use named parameters at all, just use the sequence: 如果
data.unpack()
返回一个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: 现在有两个位置 SQL参数,与从
data.unpack()
调用返回的两个值的序列匹配:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.