0

I am trying to learn how to read from a json file in Python and I am not sure how to interpret the error that I am getting I have posted my code below along with the error messages that I am getting. Any ideas? Thanks!

import json
filename = 'population.json'
with open(filename) as f:
    pop_data = json.load(f)
for pop_dict in pop_data:
    if pop_dict['Year'] == '2010':
        country_name = pop_dict['Country Name']
    population = pop_dict['Value']
    print(country_name + ":" + population)

Error Msg----

C:\Anaconda\python.exe "C:/PyCharm/Data Visual/Pop.py"
Traceback (most recent call last):
  File "C:/PyCharm/Data Visual/Pop.py", line 4, in <module>
    pop_data = json.load(f)
  File "C:\Anaconda\lib\json\__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "C:\Anaconda\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Anaconda\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Anaconda\lib\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
8
  • 2
    What's in the population.json file? Is it maybe Unicode? Commented Mar 7, 2017 at 18:16
  • 1
    Look at the very first character of your JSON file, as the error message suggests. It must be a [ or a {. If it's not, the parsing will fail. If the file looks OK in notepad, one thing I can think of is a BOM mark in a UTF-16 file. Commented Mar 7, 2017 at 18:20
  • Can you post couple of lines of 'population.json' file?. That will help narrow down problem, else there are multiple possibilities. Commented Mar 7, 2017 at 18:24
  • Use jsonlint.com to validate your json first Commented Mar 7, 2017 at 18:31
  • Country Name,Country Code,Year,Value Arab World,ARB,1960,93485943 Arab World,ARB,1961,96058179 Arab World,ARB,1962,98728995 Arab World,ARB,1963,101496308 Arab World,ARB,1964,104359772 Arab World,ARB,1965,107318159 Arab World,ARB,1966,110379639 Arab World,ARB,1967,113543760 Commented Mar 7, 2017 at 19:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.