我正在尝试解析下一个谷歌查询的json结果:
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):
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]
我不知道我做错了什么,我只读了很多教程:/
谢谢:)!
答案 0 :(得分: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)
答案 1 :(得分:1)
您可以使用rate-exchange.appspot.com
,它使用Google 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
答案 2 :(得分: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