从Google API打开Json文件在Python3中

时间:2018-04-18 07:20:35

标签: python json python-3.x

我想在python中打开一个json文件作为我可以操作和使用的对象

我有一个json文件而不是包含如下文本

{'geocoded_waypoints': [{'geocoder_status': 'OK', 'place_id': 'ChIJtxsqpbgEdkgRSCY1a5fQpDA', 'types': ['airport', 'establishment', 'point_of_interest']}, {'geocoder_status': 'OK', 'place_id': 'ChIJdd4hrwug2EcRmSrV3Vo6llI', 'types': ['locality', 'political']}], 'routes': ......

...

我从google transit api,I know that json doesn't look like the above text收到了这个json文本,但谷歌过境给了我什么,这就是我必须要做的事情。

我已尝试this method

>>> data = json.load(open('gmap_routes.json'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

this method我试图在其中修复unicode字符,但它不起作用

>>> import json
>>> with open("gmap_routes.json") as f:
...     json.load(f.encode("ascii","replace"))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'encode'

我也尝试了python2一段时间并得到了类似的结果,所以我回到了python3

1 个答案:

答案 0 :(得分:1)

是的,那些&#34;&#39;&#34;字符是问题。

您需要通过调用file.read()而不是文件本身对文件内容执行替换操作 - 这将返回一个字符串,因此请使用json.loads而不是json.load结果:

    import json
    file = open("some_file.json")
    with file as f:
    data = json.loads(f.read().replace("'", "\""))