【发布时间】:2018-09-28 07:56:10
【问题描述】:
我想在 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 文本,但这是 google transit 给我的,所以这就是我必须使用的。
我试过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
【问题讨论】:
-
这是错误的 json。有package可以处理。我怀疑您获取数据的方式存在问题。谷歌 API 不应该给你格式错误的 JSON。
-
encode是 unicode 对象的一种方法,我在您的代码中看不到f声明。也许您可以尝试在对象中加载 json,转换为 unicode,然后执行编码。
标签: python json python-3.x