我理解如何从我正在运行的phant服务器获取json字符串,但是我需要使用以下格式构建一个文本文件:label = value,每个文件都在一个单独的行上。我一直在寻找一种方法来做到这一点。需要一些帮助。
#!/usr/bin/env python
import json,requests
url = "http://192.168.250.55:8080/output/8Bl0DlDexPCpE21gZNads3ZJLpAx/latest.json"
data = json.loads(requests.get(urlsoc).text)
print data
Here is the output from this:
[{u'tempc': u'17.1500', u'altm': u'62.5088', u'tempf': u'62.8700', u'timestamp': u'2017-01-07T17:43:20.870Z', u'windspeedmph': u'0.0000', u'altf': u'205.0813', u'rainin': u'0.0000', u'wifion': u'0', u'humidity': u'27.0000', u'winddir': u'180', u'rainmm': u'0.0000', u'windspeedkmph': u'0.0000', u'voltage': u'3.9787', u'kilopascals': u'100.6010', u'dewptf': u'28.4106', u'soc': u'74.0547', u'dailyrainin': u'0.2750', u'dewptc': u'-1.9941'}]
那么如何将此信息转换为换行分隔对并写入文件,使其如下所示:
tempc = 17.1500
ALTM = 62.5088 等....
答案 0 :(得分:0)
只需遍历items
数组的每个元素中的data
(键,值对),然后使用字符串格式输出它们。
import json, requests
url = 'https://data.sparkfun.com/output/9JKlQbq6YMIAVN2Yg6v6/latest.json'
data = json.loads(requests.get(url).text)
with open('outfile', 'w') as f:
for item in data:
for key, value in item.items():
f.write('%s=%s' % (key, value,))
f.write('\n')
如果您从该端点返回了unicode数据,则可以使用codecs.open
代替open
。
处理时间戳字段解析/等。我通常建议dateutil
pip install dateutil
现在在你的代码中:
from dateutil import parser
. . .
with open('outfile', 'w') as f:
for item in data:
dt_timestamp = item.get('timestamp')
if dt_timestamp:
dt_timestamp = parser.parse(dt_timestamp)
# convert the python `datetime` however you would like
item['timestamp'] = dt_timestamp
for key, value in item.items():
f.write('%s=%s' % (key, value,))
f.write('\n')