如何在Python中读取简单的Json结果(从Google计算器)? [英] How to Read a Simple Json Result (from Google calculator) in Python?
本文介绍了如何在Python中读取简单的Json结果(从Google计算器)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从下一个Google查询中解析json结果:
I'm trying to parse a json result from the next google Query:
http://www.google.com/ig /calculator?hl = zh-CN& q = 1USD =?MXN
结果是这样的:
{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 :/
谢谢:)!
推荐答案
这不是JSON,但您仍然可以自己解析它-像这样:
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
您还可以将格式固定为json,然后使用json解析器,如下所示:
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)
这篇关于如何在Python中读取简单的Json结果(从Google计算器)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文