python + json 与 curl 的问题
Problems with python + json vs. curl
所以当我 运行 python 代码服务器 (google) 给我的响应与我 运行 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 数据结构(在本例中为字典),则只需要编码。
所以当我 运行 python 代码服务器 (google) 给我的响应与我 运行 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 数据结构(在本例中为字典),则只需要编码。