Python 如何把数据写成 JSON 文件?


#1

如何把一个 dict 或者 list 变量持久化成 JSON 文件?


#2
import json

with open('./output.json', 'w') as f:
    json.dump(result, f)

如果想生成的 json 文件比较可读,可以使用 indent 参数:

import json

with open('./output.json', 'w') as f:
    json.dump(result, f, indent = 4)

数据里面有中文字符?用 utf8 编码写:

import io, json
with io.open('./countries-1.json', 'w', encoding='utf8') as f:
    f.write(unicode(json.dumps(result, indent = 4, ensure_ascii=False)))

even better, 同时支持 python 2/3

# -*- coding: utf-8 -*-

import json

# Make it work for both Python 2 and 3, with Unicode
import io
try:
    to_unicode = unicode
except NameError:
    to_unicode = str 

with io.open('./countries-1.json', 'w', encoding='utf8') as f:
    f.write(to_unicode(json.dumps(result, indent = 4, ensure_ascii=False)))