Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从我的phant服务器执行JSON请求以构建数据文件_Python_Json_String - Fatal编程技术网

Python 从我的phant服务器执行JSON请求以构建数据文件

Python 从我的phant服务器执行JSON请求以构建数据文件,python,json,string,Python,Json,String,我知道如何从正在运行的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(re

我知道如何从正在运行的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
等等,

只需迭代
数据
数组(键、值对)每个元素中的
,然后使用字符串格式输出它们

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

请原谅我的无知,我是个不折不扣的人,但是运行这段代码会产生一个错误,抱怨没有定义密钥。我是否为每个数据对运行此代码,并相应地更改key的值?@RobertMantel:上面的代码中有一个输入错误。我已经对它进行了更新,以便它可以更好地工作。感谢更新…似乎仍然抛出此错误:AttributeError:'dict'对象没有属性'item'。您可以对我的代码进行一些更改以测试它,因为我有这个私有的phant服务器,但这里也有一个公共流:get中的urlsoc也应该是url。我只是在提供的端点上尝试了这段代码,它工作得很好。我想你把
items
拼错为
item
。至于从您的原始帖子复制的
urlsoc
/
url
,该url是https