The task is to get json from the web and write the result to report.json. There are two files in the folder: test2.py and report.json (empty).

Code:

import requests import json r = requests.get('https://www.wikidata.org//w/api.php?action=query&format=json&meta=siteinfo&siprop=namespaces') report = r.json() print(report) with open('report.json') as report: data = json.load(report) print(data) 

Result:

 /Library/Frameworks/Python.framework/Versions/3.5/bin/python3 "/Volumes/My Files/Python/iikoBot/test2.py" {'batchcomplete': '','query': {'namespaces': ...тело json... 'case': 'first-letter'}}}} Traceback (most recent call last): File "/Volumes/My Files/Python/iikoBot/test2.py", line 8, in <module> data = json.load(report) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 268, in load parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 319, in loads return _default_decoder.decode(s) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/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.5/lib/python3.5/json/decoder.py", line 357, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Process finished with exit code 1 

    1 answer 1

    you have several errors at once, in my opinion:

    1. open('report.json') - by default, opens the file for reading, not for writing

    2. json.load reads JSON from a file, and you need to write

    Try this:

     import requests import json import codecs r = requests.get('https://www.wikidata.org//w/api.php?action=query&format=json&meta=siteinfo&siprop=namespaces') with codecs.open('report.json', 'w', encoding='utf-8') as f: json.dump(r.json(), f, ensure_ascii=False) 
    • Thank you for the prompt response. Everything turned out, but if there are Russian words in jsone, they are displayed like this: "Conception": "\ u0414 \ u0430 \ u043d \ u0438 \ u043b \ u043e \ u0432 \ u0441 \ u043a \ u0438 \ u0439" - DmitryC
    • @DmitryC, I corrected the answer - try codecs - this should work with Python 2 & 3 - MaxU
    • with codecs.open ('report.json', 'w', encoding = 'utf-8') as report: data = json.dump (r.json (), report) print (data) did not help :( - DmitryC
    • @DmitryC, can you give a URL with Russian JSON for a test? - MaxU
    • one
      I decided this way: with open ('report.json', 'w') as report: data = json.dump (r.json (), report, ensure_ascii = False) print (data) - DmitryC