我想使用python将以下JSON格式的字符串发布到端点:
{"station-id": "FMAT2", "lon": "-97.37055556", "value": "8.70", "lat": "32.80805556", "data-type": "PCIRR", "time": "210811", "date": "170417"}
但是当我发送数据时,代码本身会将上述字符串的任何一部分添加到以下字符串中,如下所示:
"{""station-id"": ""FMAT2"", ""lon"": ""-97.37055556"", ""value"": ""8.62"", ""lat"": ""32.80805556"", ""data-type"": ""PCIRR"", ""time"": ""210440"", ""date"": ""170417""}"
你能不能让我知道为什么会发生这样的事情以及如何避免它。必须要说的是,我得到了响应400和429.以下是代码:
import os
import requests
from os import listdir
from os.path import isfile, join
from timeit import default_timer
start = default_timer()
files_in_dir = [ f for f in listdir('C:/Users/bxr5813/Desktop/Send data to
map') if isfile(join('C:/Users/bxr5813/Desktop/Send data to map',f)) ]
matching = [s for s in files_in_dir if "json.csv" in s]
if len(matching)==0:
print "No new report at this time"
for i in range(0,len(matching)):
filename=matching[i]
with open(filename,"r") as f:
content=f.readlines()
for j in range(0, len(content)):
line=content[j]
url = 'https://fathomless-journey-
39482.herokuapp.com/observations'
headers = {"Content-Type":"application/json", "Accept":
"text/plain", "X-Api-Key": 'lmENUdfazMd5STedwFgodgts'}
r = requests.post(url, data=line, headers=headers)
print r
print line
j+=1
f.close()
#os.remove(filename)
duration = (default_timer() - start)
print "Runnung time is "+str(duration)+" Seconds that is "+str(duration/60)+"
minutes"
您可以将JSON字符串放入.csv文件中,文件名应包含json.csv。
答案 0 :(得分:1)
在您的requests.post(...)行中使用data=json.dumps(line)
。在服务器端,使用incoming = json.loads(line)
答案 1 :(得分:0)
为了解决这个问题,我使用以下代码来替换""用"。然后,问题解决了。
line = line.replace ('""','"')
line=line.replace('"{','{')
line=line.replace('}"','}')