Search code examples
pythonjsongoogle-mapscurlgoogle-geolocation

Problems with python + json vs. curl


so when I run the python code the server (google) give me a different response than when I run curl command. Can someone tell me where I'm wrong please?

code:

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

And the command is:

curl -d @file2.json -H "Content-Type: application/json" -i "https://www.googleapis.com/geolocation/v1/geolocate?key=AI..."

where file2.json contains exactly jWifi in that format. The problem is that, as said, the location returned by the code is different from the location returned by curl. I don't get error code so I thing that the syntax is correct.


Solution

  • The data is already a JSON encoded string, you don't want to encode it twice.

    Pass it in without encoding it again:

    jWifiReport = urllib2.urlopen(req, jWifi).read()
    

    You only need to encode if you have a Python data structure (a dictionary in this case).