Skip to content

Instantly share code, notes, and snippets.

@Ostapp
Created February 14, 2016 20:25
Show Gist options
  • Save Ostapp/7a29291317a7eb6394bf to your computer and use it in GitHub Desktop.
Save Ostapp/7a29291317a7eb6394bf to your computer and use it in GitHub Desktop.

JSON reading and writing

import json
data = {
'e': 'abc def',
'b': 2,
'c': True,
'd': [4, 5, 6]
}
# step 1, variable -> str
json_str = json.dumps(data, indent=2)
# step 2, str -> file
with open('example.json', 'w') as f:
f.write(json_str)
import json
# read file -> json_str
with open('example.json') as f:
json_str = f.read()
# json_str -> variable
data = json.loads(json_str)
import codecs
import json
def read_json(path):
with codecs.open(path, encoding='utf-8') as infile:
return json.loads(infile.read())
def write_json(path, data):
with codecs.open(path, 'w', encoding='utf-8') as outfile:
json.dump(data, outfile, indent=2, ensure_ascii=False, sort_keys=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment