java 将json写入txt_如何将JSON数据写入文件?

使用Python 2 3读写JSON文件;适用于unicode

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

import json

# Make it work for Python 2+3 and with Unicode

import io

try:

to_unicode = unicode

except NameError:

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 file

with 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 file

with open('data.json') as data_file:

data_loaded = json.load(data_file)

print(data == data_loaded)

indent :使用4个空格缩进每个条目,例如当一个新的dict启动时(否则所有都将在一行),

sort_keys :对词典的键进行排序 . 如果要将json文件与diff工具进行比较/将它们置于版本控制之下,这非常有用 .

separators :防止Python添加尾随空格

带包

看看我的实用程序包mpu,看一个超级简单易记的实用程序:

import mpu.io

data = mpu.io.read('example.json')

mpu.io.write('example.json', data)

创建了JSON文件

{

"a list":[

1,

42,

3.141,

1337,

"help",

"€"

],

"a string":"bla",

"another dict":{

"foo":"bar",

"key":"value",

"the answer":42

}

}

公共文件结尾

.json

替代品

对于您的应用程序,以下可能很重要:

其他编程语言的支持

读/写性能

紧凑度(文件大小)

如果你正在寻找一种制作配置文件的方法,你可能想阅读我的短文Configuration files in Python


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部