Json:每行保存一个dict

时间:2017-12-19 23:49:32

标签: python json

如何将python词典列表保存到文件中,其中每个dict将保存在一行中?我知道我可以使用json.dump来保存字典列表。但我只能以紧凑的形式保存列表(完整列表在一行中)或缩进,其中所有字典键都添加了换行符。

编辑:

我希望我的最终file.json看起来像这样:

[{key1:value,key2:value},
{key1:value,key2:value},
...
{key1:value,key2:value}]

4 个答案:

答案 0 :(得分:4)

我同意另一个回复 - 您可以做的最好是单独json.dump每个dict并手动编写逗号和换行符。我将如何做到这一点:

import json

data = [
    {"key01":"value","key02":"value"},
    {"key11":"value","key12":"value"},
    {"key21":"value","key22":"value"}
]

import json
with open('file.json', 'w') as fp:
    fp.write(
        '[' +
        ',\n'.join(json.dumps(i) for i in data) +
        ']\n')

结果:

[{"key01": "value", "key02": "value"},
{"key12": "value", "key11": "value"},
{"key22": "value", "key21": "value"}]

答案 1 :(得分:1)

您的最终file.json示例不是有效的JSON。假设你想用它传达表单,你可以尝试扩展json.JSONEncoder,但假设你的字典中没有嵌套结构,快速而肮脏的方法就是手动构建文件,即

import json

your_data = [  # lets define some test data
    {"key1.0": "value", "key2.0": "value"},
    {"key1.1": "value", "key2.1": "value"},
    {"key1.2": "value", "key2.2": "value"},
    {"key1.3": "value", "key2.3": "value"},
]

with open("file.json", "w") as f:  # open our file for writing
    f.write("[")  # begin a JSON array
    if your_data:  # a check to determine that our array is not empty
        for element in your_data:  # now loop through your elements one by one
            json.dump(element, f)  # JSON encode each element and write it to the file
            f.write(",\n")  # close the element entry with a comma and a new line
        f.seek(-3, 1)  # go back to the last separator to clear out the comma
    f.write("]")  # end the JSON array
    f.truncate()  # remove the rest, just in case

将产生:

[{"key1.0": "value", "key2.0": "value"},
{"key1.1": "value", "key2.1": "value"},
{"key1.2": "value", "key2.2": "value"},
{"key1.3": "value", "key2.3": "value"}]

答案 2 :(得分:1)

为了好玩,我将my answer改编为另一个有点相关的问题,让它做你想做的事。
请注意,目前它只会更改dict的格式,如果它在列表中。

import _ctypes
import json
import re

class OneDictPerLine(object):
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        if not isinstance(self.value, list):
            return repr(self.value)
        else:  # Sort the representation of any dicts in the list.
            reps = ('{{{}}}'.format(', '.join(
                        ('{!r}: {}'.format(k, v) for k, v in sorted(v.items()))
                    )) if isinstance(v, dict)
                        else
                    repr(v) for v in self.value)
            return '[' + ',\n'.join(reps) + ']'


def di(obj_id):
    """ Reverse of id() function. """
    # from https://stackoverflow.com/a/15012814/355230
    return _ctypes.PyObj_FromPtr(obj_id)


class MyEncoder(json.JSONEncoder):
    FORMAT_SPEC = "@@{}@@"
    regex = re.compile(FORMAT_SPEC.format(r"(\d+)"))

    def default(self, obj):
        return (self.FORMAT_SPEC.format(id(obj)) if isinstance(obj, OneDictPerLine)
                else super(MyEncoder, self).default(obj))

    def encode(self, obj):
        format_spec = self.FORMAT_SPEC  # Local var to expedite access.
        json_repr = super(MyEncoder, self).encode(obj)  # Default JSON repr.

        # Replace any marked-up object ids in the JSON repr with the value
        # returned from the repr() of the corresponding Python object.
        for match in self.regex.finditer(json_repr):
            id = int(match.group(1))
            # Replace marked-up id with actual Python object repr().
            json_repr = json_repr.replace(
                       '"{}"'.format(format_spec.format(id)), repr(di(id)))

        return json_repr

样本用法:

data = [
    {"key01":"value","key02":"value"},
    {"key11":"value","key12":"value"},
    {"key21":"value","key22":"value"}
]

print(json.dumps(OneDictPerLine(data), cls=MyEncoder))

输出:

[{'key01': value, 'key02': value},
{'key11': value, 'key12': value},
{'key21': value, 'key22': value}]

答案 3 :(得分:0)

这可能无法完全生成OP所需的内容,但是通常要打印漂亮的JSON,可以添加一个indent参数:

json.dump(data, json_path.open("w"), indent=2)

示例输出:

  "k07-689z-01": {
    "image_path": "v_1280/k07-689z-01.tif",
    "gt": "Instead he said: Will that be better? She nodded: And she might add: And don't forget to",
    "components": [
      "k07-689z-01a.tif",
      "k07-689z-01b.tif",
    ],
  },

这会将一行字典转换为一个字典,其中每个键/指针都有自己的行。您还可以更改“分隔符”命令来更改行的分割方式,请参见https://docs.python.org/3.7/library/json.html#basic-usage