首页 > 解决方案 > 如何动态填充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()

标签: pythonarraysjsonraspberry-pi4

解决方案


无需在每次迭代中进行文件写入操作,您可以尝试在循环结束后一次写入所有数据。


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()

推荐阅读