我正在尝试从此链接加载一个 json 文件:
https://github.com/annexare/Countries/tree/master/data
f = open ('countries.json')
data = json.load(f)
我收到以下错误:
JSONDecodeError Traceback (most recent call last)
<ipython-input-271-3c5bb9db18ae> in <module>
1 f = open ('countries.json')
----> 2 data = json.load(f)
~/anaconda3/lib/python3.7/json/__init__.py in load(fp, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
294 cls=cls, object_hook=object_hook,
295 parse_float=parse_float, parse_int=parse_int,
--> 296 parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
297
298
~/anaconda3/lib/python3.7/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
346 parse_int is None and parse_float is None and
347 parse_constant is None and object_pairs_hook is None and not kw):
--> 348 return _default_decoder.decode(s)
349 if cls is None:
350 cls = JSONDecoder
~/anaconda3/lib/python3.7/json/decoder.py in decode(self, s, _w)
335
336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
338 end = _w(s, end).end()
339 if end != len(s):
~/anaconda3/lib/python3.7/json/decoder.py in raw_decode(self, s, idx)
353 obj, end = self.scan_once(s, idx)
354 except StopIteration as err:
--> 355 raise JSONDecodeError("Expecting value", s, err.value) from None
356 return obj, end
JSONDecodeError: Expecting value: line 7 column 1 (char 6)**
以下是 JSON 文件的前几行:
{
"AD": {
"name": "Andorra",
"native": "Andorra",
"phone": "376",
"continent": "EU",
"capital": "Andorra la Vella",
"currency": "EUR",
"languages": [
"ca"
]
},
如果您有建议,请告诉我。
所以主要问题是编码和更改你的代码
import json
f = open(file='countries.json',mode='rb')
contents = f.read()
data = json.loads(contents)
应该解决问题。
见下文(它没有问题(
import requests
r = requests.get('https://raw.githubusercontent.com/annexare/Countries/master/data/countries.json')
if r.status_code == 200:
data = r.json()
print(data)
r = requests.get('https://raw.githubusercontent.com/annexare/Countries/master/data/languages.json')
if r.status_code == 200:
data = r.json()
print(data)
您发布的代码绝对没问题。这可能是潜在的问题之一 - 也许您尝试在同一文件流(f
(上多次使用json.load(f)
。为了检查这是否是问题所在,请尝试data = json.load(open('countries.json'))
。 这样,将始终重新创建文件流