【问题标题】:Opening a Json File From Google API's In Python3在 Python3 中从 Google API 中打开 Json 文件
【发布时间】: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


【解决方案1】:

是的,那些“'”字符是问题所在。

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

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

【讨论】:

  • 对我来说,这返回与第一种方法相同的错误json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
猜你喜欢
  • 1970-01-01
  • 2019-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
  • 2021-04-30
相关资源
最近更新 更多