python - 如何动态填充json文件
问题描述
我使用这段代码将一些数据从 Pi 发送到云端(需要采用 json 格式)。但是我也想将数据保存在创建的 json 文件中。有关发送到云的所有内容都可以正常工作,因为我可以一一发送值,但是在 json 文件中我遇到了一些问题。任何人都可以通过我的命令看到:
with open('json_body.json', 'w') as json_file:
json.dump(data, json_file)
我创建了一个 json 文件,但只保存了最新的“数据”值。有谁知道我怎样才能保存所有这些?我必须先使用数组或列表来保存它们吗?任何建议都是有帮助的。先感谢您!
while True:
acc = ReadChannel(acc_channel)
# Print out results
print("--------------------------------------------")
print("Acc : " , acc , ",Acc in volts", ConvertVolts(acc,2))
data = {}
data['acceleration'] = acc
json_body = json.dumps(data)
print("Sending message: ", json_body)
counter = counter + 1
print(counter)
with open('json_body.json', 'w') as json_file:
json.dump(data, json_file)
await device_client.send_message(json_body)
# Wait before repeating loop
time.sleep(delay)
await device_client.disconnect()
解决方案
无需在每次迭代中进行文件写入操作,您可以尝试在循环结束后一次写入所有数据。
temporary_json = []
while True:
acc = ReadChannel(acc_channel)
# Print out results
print("--------------------------------------------")
print("Acc : ", acc, ",Acc in volts", ConvertVolts(acc, 2))
data = {}
data["acceleration"] = acc
json_body = json.dumps(data)
print("Sending message: ", json_body)
counter = counter + 1
print(counter)
temporary_json.append(json.dumps(data))
await device_client.send_message(json_body)
# Wait before repeating loop
time.sleep(delay)
with open("json_body.json", "w") as json_file:
proper_json = ",".join(temporary_json) # making a valid json out of temporary json
json.dump(proper_json, json_file)
awaitdevice_client.disconnect()
推荐阅读
- python - GitPython 列出分支,如果它们匹配某个名称模式,则删除
- node.js - 是否可以为 NodeJS 工作线程构造函数使用字符串?
- javascript - 无法使用 react-router-dom 5.2.0 编写嵌套路由?
- typescript - 由于以下原因无法运行 mocha:TS2451:无法重新声明块范围变量 x
- spring - 侦听器在使用 EmbeddedKafka Spring 进行测试时不使用消息
- r - R脚本生成两个相同列表的所有组合,包括不完整列表
- java - Apache James 中的嵌入式 Tomcat
- python - 使用带有整数的 Dataframe 调用,如列名
- unit-testing - 返回的模拟对象具有所有导致测试失败的空字段
- javascript - onRowAdd 发送到数据库后更新 Material UI 表