python + json与curl的问题
问题描述:
所以当我运行Python代码时,服务器(google)给了我一个与运行curl命令不同的响应。有人能告诉我我错在哪里吗?python + json与curl的问题
代码:
import urllib2, simplejson
def MapsWIFI(card):
req = urllib2.Request("https://www.googleapis.com/geolocation/v1/geolocate?key=AI...")
jWifi = """
{
"wifiAccessPoints": [
{
"macAddress": "64:D1:A3:0A:11:65",
"channel": 6,
},
... #some AP here
]
}
"""
print jWifi
req.add_header("Content-Type", "application/json")
jWifiReport = urllib2.urlopen(req,simplejson.dumps(jWifi)).read()
print jWifiReport
APdetected = str(len(wifiCell))
mapsDict = simplejson.loads(jWifiReport)
location = str(mapsDict.get("location",{}))[1:-1]
accuracy = "Accuracy: "+str(mapsDict.get("accuracy",{}))[1:-1]
mapMe = "|---"+location.split(",")[0]+"\n|---"+location.split(",")[1][1:]+"\n|---$
return mapMe
MapsWIFI("wlp8s0")
和命令是:
curl -d @file2.json -H "Content-Type: application/json" -i "https://www.googleapis.com/geolocation/v1/geolocate?key=AI..."
其中file2.json正好包含jWifi该格式。 问题是,如上所述,代码返回的位置与curl返回的位置不同。我没有得到错误代码,所以我认为语法是正确的。
答
数据是已经一个JSON编码的字符串,你不想编码它两次。
通过它在没有再次对其进行编码:
jWifiReport = urllib2.urlopen(req, jWifi).read()
你只需要,如果你有一个Python数据结构(在这种情况下字典)来编码。
出于兴趣,为什么要使用'simplejson'库? Python 2.7带有'json'模块,它与*完全相同的项目*。 –
是的,你是对的。但是这是一个旨在尽可能便携的项目的一部分,所以这应该与其他版本兼容。 – Pielco11