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
johankent30
  • 65
  • 2
  • 3
  • 11
  • 2
    What's in the `population.json` file? Is it maybe Unicode? – kichik Mar 07 '17 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. – 9000 Mar 07 '17 at 18:20
  • Can you post couple of lines of 'population.json' file?. That will help narrow down problem, else there are multiple possibilities. – Anil_M Mar 07 '17 at 18:24
  • Use http://jsonlint.com/ to validate your json first – somesingsomsing Mar 07 '17 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 – johankent30 Mar 07 '17 at 19:09
  • I posted a snip from my json file above. I am seeing that it is not properly formatted. Excuse my lack of knowledge here, but what is a BOM mark in a UTF-16? And are you saying that if I convert the json file to that it will fix my error? – johankent30 Mar 07 '17 at 19:14
  • It's ^^ totally not a JSON file, but it's likely a valid CSV file. – 9000 Mar 07 '17 at 19:31
  • I figured out what I needed to do to get an actual json file. Thanks for the help everyone – johankent30 Mar 07 '17 at 19:40

0 Answers0