我正在尝试设置测试脚本,以了解如何使用python生成和读取JSON。
我想从简单的事情开始,当按下按钮生成时,当发布添加并结束该事件时,id为1。在脚本底部有一个我需要发送到vis.js时间轴的JSON示例... id也喜欢从python中读取JSON文件,看看最后一个id是什么,然后从那里添加,也许是如果我需要创建一个新事件或在结束时添加,取决于按下和发布之间的时间。
#!/usr/bin/python
import RPi.GPIO as GPIO
import datetime
import json
import os.path
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
datain = {}
dataout = {}
if os.path.isfile("/home/pi/data.json"):
with open('data.json', 'r') as outfile:
datain = json.load(outfile)
while True:
GPIO.wait_for_edge(23, GPIO.RISING)
print("Button 1 Pressed")
print(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
dataout ['id'] = "1"
dataout ['content'] = "Button Pressed"
dataout ['start'] = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
GPIO.wait_for_edge(23, GPIO.FALLING)
print("Button 1 Released")
print(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
dataout ["end"] = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
with open('data.json', 'ab+') as outfile:
json.dump(dataout, outfile, sort_keys=False)
GPIO.cleanup()
#{
#id: 1,
# content: 'First event',
# start: '2014-08-01'
#}, {
# id: 2,
# content: 'Pi and Mash',
# start: '2014-08-08'}
修改
结果我错误地生成了JSON它不是经过验证的JSON文件,我修复了它,现在的问题是我可以向对象添加/追加属性如何添加新事件? ...
#!/usr/bin/python
import RPi.GPIO as GPIO
import datetime
import json
import os.path
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)
datain = {}
dataout = {}
if os.path.isfile("/home/pi/data.json"):
with open('data.json', 'r') as outfile:
datain = json.load(outfile)
while True:
GPIO.wait_for_edge(23, GPIO.RISING)
print("Button 1 Pressed")
print(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
dataout = {"Events":[{"content": "Button Pressed", "start": datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'), "id": "1" }]}
GPIO.wait_for_edge(23, GPIO.FALLING)
print("Button 1 Released")
print(datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S'))
dataout.append({"end"})
data[0]['end'] = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
with open('data.json', 'ab+') as outfile:
json.dump(dataout, outfile, sort_keys=False, indent=4)
GPIO.cleanup()
更新
我已成功完成上述任务:
#dataout.append({"end"})
dataout["Events"][0]["end"] = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
** UPDATE2 *
我也注意到这段代码会创建新对象(new + old)作为重复的根...
解决方案是使用重写方法打开转储文件。
with open('data.json', 'wb+') as outfile:
json.dump(dataout, outfile, sort_keys=False, indent=4)