[英]Python writing to file and json returns None/null instead of value
I'm trying to write data to a file with the following code我正在尝试使用以下代码将数据写入文件
#!/usr/bin/python37all
print('Content-type: text/html\n\n')
import cgi
from Alarm import *
import json
htmldata = cgi.FieldStorage()
alarm_time = htmldata.getvalue('alarm_time')
alarm_date = htmldata.getvalue('alarm_date')
print(alarm_time,alarm_date)
data = {'time':alarm_time,'date':alarm_date}
# print(data['time'],data['date'])
with open('alarm_data.txt','w') as f:
json.dump(data,f)
...
but when opening the the file, I get the following output: {'time':null,'date':null}
但是打开文件时,我得到以下 output:
{'time':null,'date':null}
The print statement returns what I except it to: 14:26 2020-12-12
. print 语句将 I 除了它之外的内容返回到:
14:26 2020-12-12
。 I've tried this same method with f.write()
but it returns both values as None
.我用
f.write()
尝试过同样的方法,但它返回两个值都为None
。 This is being run on a raspberry pi.这是在树莓派上运行的。 Why aren't the correct values being written?
为什么没有写入正确的值?
--EDIT-- The json string I expect to see is the following: {'time':'14:26','date':'2020-12-12'}
--EDIT-- 我希望看到的 json 字符串如下:
{'time':'14:26','date':'2020-12-12'}
Perhaps you meant:也许你的意思是:
data = {'time':str(alarm_time), 'date':str(alarm_date)}
I would expect to see your file contents like this:我希望看到你的文件内容是这样的:
{"time":"14:26","date":"2020-12-12"}
Note the double quotes: "
. json
is very strict about these things, so don't fool yourself into having single quotes '
in a file and expecting json
to parse it.注意双引号:
"
. json
对这些事情非常严格,所以不要自欺欺人地在文件中使用单引号'
并期望json
解析它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.