在Json中将多个变量转储到磁盘.每行一个变量 [英] Dumping multiple variables to disk in Json. One variable per line

查看:88
本文介绍了在Json中将多个变量转储到磁盘.每行一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想使用Json将多个变量转储到磁盘.他们通常这样做的方式是,在字典中将变量创建为条目,然后将字典转储到磁盘:

Say I want to dump multiple variables to disk with Json. They way I usually do this is by creating my variables as entries in a dictionary and then dumping the dictionary to disk:

with open(p_out, 'wb') as fp:
    json.dump(my_dictionary, fp)

这将创建一个json文件,该字典将字典存储在长行中:

This creates a json file where the dictionary is saved in a long line:

{"variable_1": something, "variable_2" something_else, ...}

我不喜欢.我希望将变量以每行一个变量的形式转储到文本文件中,例如以下几行:

which I don't like. I would prefer to have my variables dumped into the text file with one variable per line, e.g something along these lines:

{variable_1: something\n
 variable_2: something\n
 variable_3: something_else}

是否可以在Python中使用Json做到这一点?

Is there a way to do this with Json in Python?

推荐答案

indent选项设置为0或更多:

with open(p_out, 'wb') as fp:
    json.dump(my_dictionary, fp, indent=0)

来自文档:

如果 indent 是非负整数,则JSON数组元素和对象成员将以该缩进级别进行漂亮打印.缩进级别0或负数将仅插入换行符. None(默认)选择最紧凑的表示形式.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0, or negative, will only insert newlines. None (the default) selects the most compact representation.

您的示例将输出为:

{
"variable_2": "something_else", 
"variable_1": "something"
}

这篇关于在Json中将多个变量转储到磁盘.每行一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆