-1

I have a task to work with file https://github.com/mledoze/countries/blob/master/countries.json , which is pretty big. Firstly, I downloaded it with wget and tried to work with 0 element:

import wget

print('Beginning file download with wget module')

url = 'https://raw.githubusercontent.com/mledoze/countries/master/countries.json'
wget.download(url, 'сountries.json')

handle = open("сountries.json", "r")
data = handle.read()
print(data[0])
handle.close()

However, the whole json file was recognized as "str", and as 0 element I recieved just "[" how can I fix this?

enter image description here

Fedor Peplin
  • 149
  • 1
  • 8
  • Perhaps you meant to use the built in `json` module to decode the string into a list. – quamrana May 27 '20 at 14:42
  • 2
    Yes, JSON *is* a string. Reading from any file, you'll always read strings. You will never read objects straight from a file. You'll have to decode the JSON using `json.load`. – deceze May 27 '20 at 14:42

1 Answers1

2

data is a string. You have to decode it to (apparently) a list first.

import json


with open("countries.json") as handle:
    data = json.load(handle)
    print(data[0])
chepner
  • 497,756
  • 71
  • 530
  • 681
  • FileNotFoundError: [Errno 2] No such file or directory: 'countries.json', but I see clearly that in the working project folder there is a file "countries.json" – Fedor Peplin May 27 '20 at 14:45