Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you’ll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.
I would answer with slight modification with aforementioned answers and that is to write a prettified JSON file which human eyes can read better. For this, pass sort_keys as True and indent with 4 space characters and you are good to go. Also take care of ensuring that the ascii codes will not be written in your JSON file:
with open('data.txt', 'w') as outfile:
json.dump(jsonData, outfile, sort_keys = True, indent = 4,
ensure_ascii = False)
回答 3
使用Python 2 + 3读写JSON文件;与unicode一起使用
# -*- coding: utf-8 -*-import json
# Make it work for Python 2+3 and with Unicodeimport io
try:
to_unicode = unicode
exceptNameError:
to_unicode = str
# Define data
data ={'a list':[1,42,3.141,1337,'help', u'€'],'a string':'bla','another dict':{'foo':'bar','key':'value','the answer':42}}# Write JSON filewith io.open('data.json','w', encoding='utf8')as outfile:
str_ = json.dumps(data,
indent=4, sort_keys=True,
separators=(',',': '), ensure_ascii=False)
outfile.write(to_unicode(str_))# Read JSON filewith open('data.json')as data_file:
data_loaded = json.load(data_file)print(data == data_loaded)
For those of you who are trying to dump greek or other “exotic” languages such as me but are also having problems (unicode errors) with weird characters such as the peace symbol (\u262E) or others which are often contained in json formated data such as Twitter’s, the solution could be as follows (sort_keys is obviously optional):
import codecs, json
with codecs.open('data.json', 'w', 'utf8') as f:
f.write(json.dumps(data, sort_keys = True, ensure_ascii=False))
I don’t have enough reputation to add in comments, so I just write some of my findings of this annoying TypeError here:
Basically, I think it’s a bug in the json.dump() function in Python 2 only – It can’t dump a Python (dictionary / list) data containing non-ASCII characters, even you open the file with the encoding = 'utf-8' parameter. (i.e. No matter what you do). But, json.dumps() works on both Python 2 and 3.
To illustrate this, following up phihag’s answer: the code in his answer breaks in Python 2 with exception TypeError: must be unicode, not str, if data contains non-ASCII characters. (Python 2.7.6, Debian):
import json
data = {u'\u0430\u0431\u0432\u0433\u0434': 1} #{u'абвгд': 1}
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
Also, if you need to debug improperly formatted JSON, and want a helpful error message, use import simplejson library, instead of import json (functions should be the same)
import json
with open('data.txt')as json_file:
data = json.load(json_file)for p in data['people']:print('Name: '+ p['name'])print('Website: '+ p['website'])print('From: '+ p['from'])print('')
import json
with open('data.txt') as json_file:
data = json.load(json_file)
for p in data['people']:
print('Name: ' + p['name'])
print('Website: ' + p['website'])
print('From: ' + p['from'])
print('')
#! /usr/bin/env pythonimport json
def write_json():# create a dictionary
student_data ={"students":[]}#create a list
data_holder = student_data["students"]# just a counter
counter =0#loop through if you have multiple items.. while counter <3:
data_holder.append({'id':counter})
data_holder.append({'room':counter})
counter +=1#write the file
file_path='/tmp/student_data.json'with open(file_path,'w')as outfile:print("writing file to: ",file_path)# HERE IS WHERE THE MAGIC HAPPENS
json.dump(student_data, outfile)
outfile.close()print("done")
write_json()
All previous answers are correct here is a very simple example:
#! /usr/bin/env python
import json
def write_json():
# create a dictionary
student_data = {"students":[]}
#create a list
data_holder = student_data["students"]
# just a counter
counter = 0
#loop through if you have multiple items..
while counter < 3:
data_holder.append({'id':counter})
data_holder.append({'room':counter})
counter += 1
#write the file
file_path='/tmp/student_data.json'
with open(file_path, 'w') as outfile:
print("writing file to: ",file_path)
# HERE IS WHERE THE MAGIC HAPPENS
json.dump(student_data, outfile)
outfile.close()
print("done")
write_json()