Skip to content

Instantly share code, notes, and snippets.

@nwgat
Forked from anonymous/gist:ff138778f92bb5c927e0
Created March 20, 2016 19:31
Show Gist options
  • Save nwgat/023efc621cc991e014a8 to your computer and use it in GitHub Desktop.
Save nwgat/023efc621cc991e014a8 to your computer and use it in GitHub Desktop.
save/load python json file
ripped from http://kaira.sgo.fi/2014/05/saving-and-loading-data-in-python-with.html
## Saving a Python dictionary to disk using JSON
#!/usr/bin/python
# This only uses the json package
import json
# Create a dictionary (a key-value-pair structure in Python)
my_dict = {
'Name': 'KAIRA',
'Location': u'Kilpisj\u00E4rvi',
'Longitude': 20.76,
'Latitude': 69.07
}
# We can print the dictionary to show we have data. E.g.
print my_dict
print my_dict['Location']
# Open a file for writing
out_file = open("test.json","w")
# Save the dictionary into this file
# (the 'indent=4' is optional, but makes it more readable)
json.dump(my_dict,out_file, indent=4)
# Close the file
out_file.close()
## Loading a JSON file into a Python dictionary
#!/usr/bin/python
# This only uses the json package
import json
# Open the file for reading
in_file = open("test.json","r")
# Load the contents from the file, which creates a new dictionary
new_dict = json.load(in_file)
# Close the file... we don't need it anymore
in_file.close()
# Print the contents of our freshly loaded dictionary
print new_dict
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment