Created
February 14, 2016 20:25
-
-
Save Ostapp/7a29291317a7eb6394bf to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
# read file -> json_str | |
with open('example.json') as f: | |
json_str = f.read() | |
# json_str -> variable | |
data = json.loads(json_str) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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