How to Read a Simple Json Result (from Google calculator) in Python?
Question: I'm trying to parse a json result from the next google Query:

[http://www.google.com/ig/calculator?hl=en&q=1USD=?MXN](http://www.google.com/ig/calculator?hl=en&q=1USD=?MXN)

The result is this:

    
    
    {lhs: "1 U.S. dollar",rhs: "13.3317335 Mexican pesos",error: "",icc: true}
    

So i'm just trying to decode with this:

    
    
    import json, urllib2
    
    j=urllib2.urlopen("http://www.google.com/ig/calculator?hl=en&q=1USD=?MXN")
    print json.load(j)
    

But i'm having this error (Traceback):

    
    
    Traceback (most recent call last):
      File "/home/rafael/gitSources/PythonConcept/Monpy/negApi.py", line 4, in <module>
        print json.load(j)
      File "/usr/lib/python2.7/json/__init__.py", line 278, in load
        **kw)
      File "/usr/lib/python2.7/json/__init__.py", line 326, in loads
        return _default_decoder.decode(s)
      File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
        obj, end = self.raw_decode(s, idx=_w(s, 0).end())
      File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
        obj, end = self.scan_once(s, idx)
    ValueError: Expecting property name: line 1 column 1 (char 1)
    [Finished in 0.6s with exit code 1]
    

I don't know what i'm doing wrong, I just read many tutorials :/

Thanks :)!


Answer: This is not JSON but you can still parse it yourself - like this:

    
    
    import ast
    
    resp = '{lhs: "1 U.S. dollar",rhs: "13.3317335 Mexican pesos",error: "",icc: true}'
    
    d = {}
    for pair in resp[1:-1].split(','):
        (k,v) = pair.split(':')
        v = v.strip()
        if v == "true":
            v = "True"
        try:
            v = ast.literal_eval(v)
        except:
            print "Couldn't eval " + v
        d[k] = v
    
    print d
    

You could also fix up the formatting to be json and then use the json parser
like this:

    
    
    import json
    
    resp = '{lhs: "1 U.S. dollar",rhs: "13.3317335 Mexican pesos",error: "",icc: true}'
    
    s = "{"    
    for pair in resp[1:-1].split(','):
        (k,v) = pair.split(':')
        s += '"%s" : %s,' % (k,v)
    s = s[:-1] + "}"
    
    print json.loads(s)
    

