2012-07-11 46 views
2

我試圖解析從一個谷歌查詢一個JSON結果:如何在Python中讀取簡單的Json結果(來自Google計算器)?

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

結果是這樣的:

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

所以我只是想用這個解碼:

import json, urllib2 

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

,但我有這個錯誤(回溯):

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] 

我不知道我做錯了,我剛剛看了很多教程:/

謝謝:)!

+5

這不是JSON。 – 2012-07-11 08:03:16

+1

JSON應該是'{「lhs」:「1美元」,「rhs」:「13.3317335墨西哥比索」,「錯誤」:「」,「icc」:true}'。 – 2012-07-11 08:09:08

回答

2

這不是JSON,但你仍然可以自己分析它 - 這樣的:

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 

您也可以解決了格式爲JSON,然後使用JSON解析器是這樣的:

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) 
+0

哇,這是偉大的..但我想知道這裏發生了什麼:) – rafuru 2012-07-11 08:29:03

+0

例如,在sintax,你會從1到-1? – rafuru 2012-07-11 08:30:05

+0

string [1:-1]表示除第一個和最後一個字符以外的整個字符串,然後沿着逗號分開,然後沿着冒號分開 – 2012-07-11 08:31:06

0

這裏是你應該做的:

進口重新

s = '{lhs: "1 U.S. dollar",rhs: "13.3317335 Mexican pesos",error: "",icc: true}' 
only_numbers=re.sub(r'[^0-9,.]+', '', s) 
m = re.match(r"(\d+..),(\d+.\d+),,", only_numbers) 
currency=m.group(2) 

輸出:13.3317335

1

您可以使用rate-exchange.appspot.com,它使用谷歌API,但返回有效的JSON:

http://rate-exchange.appspot.com/currency?from=USD&to=MXN&q=1 
{"to": "MXN", "rate": 12.7523369, "from": "USD", "v": 12.7523369} 

以下是如何與requests使用它:

>>> import requests 
>>> r = requests.get('http://rate-exchange.appspot.com/currency?from=USD&to=MXN&q=1') 
>>> r.json['v'] 
12.7523369