I haven't worked with JSON files before, and I think maybe I'm just a little lost on how to pull data in. Here's my code:
# Loads data on women breastfeeding in America from the web #
import urllib.request
import json
with urllib.request.urlopen("https://chronicdata.cdc.gov/views/8hxn-cvik/rows.json?accessType=DOWNLOAD") as web_data:
data = json.loads(web_data.read().decode())
json.dump(data, web_data)
I'm trying to pull in the data from the internet, as the link itself is a webpage view, and my computer refused to let me save it onto my computer. I want to be able to manipulate the data, but I've run into several problems. With the above code, I get the following error:
---------------------------------------------------------------------------
UnsupportedOperation Traceback (most recent call last)
<ipython-input-31-7f3487bc83ea> in <module>()
6 data = json.loads(web_data.read().decode())
7 #write_data=data.write()
----> 8 json.dump(data, web_data)
~\OneDrive\Documents\Python stuff\Pythonstuff\lib\json\__init__.py in dump(obj, fp, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
178 # a debuggability cost
179 for chunk in iterable:
--> 180 fp.write(chunk)
181
182
UnsupportedOperation: write
I tried the following, thinking it had something to do with the .read():
import urllib.request
import json
with urllib.request.urlopen("https://chronicdata.cdc.gov/views/8hxn-cvik/rows.json?accessType=DOWNLOAD") as web_data:
data = json.loads(web_data.read().decode())
write_data=data.write()
json.dump(write_data, web_data)
And then I get the following error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-32-7ce187449c36> in <module>()
5 with urllib.request.urlopen("https://chronicdata.cdc.gov/views/8hxn-cvik/rows.json?accessType=DOWNLOAD") as web_data:
6 data = json.loads(web_data.read().decode())
----> 7 write_data=data.write()
8 json.dump(write_data, web_data)
AttributeError: 'dict' object has no attribute 'write'
Can someone help point me in the right direction? I'm lost as to how I can open this file and start manipulating the data. I'll eventually want to be able to manipulate some things into a data frame from there.
If I understand your question correctly, you want to write the data to a file and save it in your computer, right? Then you should open the file that you want to write to (I'm calling it rows.json
here):
import urllib.request
import json
with urllib.request.urlopen("https://chronicdata.cdc.gov/views/8hxn-cvik/rows.json?accessType=DOWNLOAD") as web_data:
data = json.loads(web_data.read().decode())
with open("rows.json", "w") as out_file:
json.dump(data, out_file)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With