How to open a json.gz file and return to dictionary in Python

Viewed 14647

I have downloaded a compressed json file and want to open it as a dictionary.

I used json.load but the data type still gives me a string. I want to extract a keyword list from the json file. Is there a way I can do it even though my data is a string? Here is my code:

import gzip
import json
with gzip.open("19.04_association_data.json.gz", "r") as f:

 data = f.read()
with open('association.json', 'w') as json_file:  
     json.dump(data.decode('utf-8'), json_file)

with open("association.json", "r") as read_it: 
     association_data = json.load(read_it) 



print(type(association_data))

#The actual output is 'str' but I expect it is 'dic'
2 Answers

In the first with block you already got the uncompressed string, no need to open it a second time.

import gzip
import json

with gzip.open("19.04_association_data.json.gz", "r") as f:
   data = f.read()
   j = json.loads (data.decode('utf-8'))
   print (type(j))

Open the file using the gzip package from the standard library (docs), then read it directly into json.loads():

import gzip
import json    

with gzip.open("19.04_association_data.json.gz", "rb") as f:
    data = json.loads(f.read(), encoding="utf-8")
Related