将二维列表写入JSON文件

时间:2017-03-10 05:25:08

标签: python json

我有一个二维列表,如:

data = [[1,2,3], [2,3,4], [4,5,6]]

我想将它写成JSON文件,如下所示:

{
    'data':[
        [1,2,3],
        [2,3,4],
        [4,5,6]
    ]
}

我得到的是:json.dumps(data, indent=4, sort_keys=True)

{
    'data':[
        [
         1,
         2,
         3
        ],
        [
         2,
         3,
         4
        ],
        [
         4,
         5,
         6]
    ]
}

以下是另一个问题How to implement custom indentation when pretty-printing with the JSON module?,但这是字典。

2 个答案:

答案 0 :(得分:2)

我认为您可以将my answer用于另一个类似的问题,以达到您想要的效果。虽然它适用于json.dumps(),但您指出由于json.dump()而出于某种原因并不存在。

在调查此事后,我发现在链接的答案中被覆盖的派生encode()的{​​{1}}方法仅在调用json.JSONEncoder时调用,而不是在调用dumps()时调用dump()被称为。{/ p>

幸运的是,我很快就能确定在这两种情况下都会调用iterencode()方法 ,所以能够通过移动代码或多或少来解决问题来自encode()并将其放入另一种方法中。

下面的代码是修订版本,其中包含以下更改:

在我对其他问题的回答中

修改了版本的代码:

from _ctypes import PyObj_FromPtr  # see https://stackoverflow.com/a/15012814/355230
import json
import re


class NoIndent(object):
    """ Value wrapper. """
    def __init__(self, value):
        if not isinstance(value, (list, tuple)):
            raise TypeError('Only lists and tuples can be wrapped')
        self.value = value


class MyEncoder(json.JSONEncoder):
    FORMAT_SPEC = '@@{}@@'  # Unique string pattern of NoIndent object ids.
    regex = re.compile(FORMAT_SPEC.format(r'(\d+)'))  # compile(r'@@(\d+)@@')

    def __init__(self, **kwargs):
        # Encoding keys to ignore when encoding NoIndent wrapped value.
        ignore = {'cls', 'indent'}

        # Save copy of any keyword argument values needed for use here.
        self._kwargs = {k: v for k, v in kwargs.items() if k not in ignore}
        super(MyEncoder, self).__init__(**kwargs)

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

    def iterencode(self, obj, **kwargs):
        format_spec = self.FORMAT_SPEC  # Local var to expedite access.

        # Replace any marked-up NoIndent wrapped values in the JSON repr
        # with the json.dumps() of the corresponding wrapped Python object.
        for encoded in super(MyEncoder, self).iterencode(obj, **kwargs):
            match = self.regex.search(encoded)
            if match:
                id = int(match.group(1))
                no_indent = PyObj_FromPtr(id)
                json_repr = json.dumps(no_indent.value, **self._kwargs)
                # Replace the matched id string with json formatted representation
                # of the corresponding Python object.
                encoded = encoded.replace(
                            '"{}"'.format(format_spec.format(id)), json_repr)

            yield encoded

将其应用于您的问题:

# Example of using it to do get the results you want.

alfa = [('a','b','c'), ('d','e','f'), ('g','h','i')]
data = [(1,2,3), (2,3,4), (4,5,6)]

data_struct = {
    'data': [NoIndent(elem) for elem in data],
    'alfa': [NoIndent(elem) for elem in alfa],
}

print(json.dumps(data_struct, cls=MyEncoder, sort_keys=True, indent=4))

# test custom JSONEncoder with json.dump()
with open('data_struct.json', 'w') as fp:
    json.dump(data_struct, fp, cls=MyEncoder, sort_keys=True, indent=4)
    fp.write('\n')  # Add a newline to very end (optional).

显示的输出(以及data_struct.json文件的结果内容):

{
    "alfa": [
        ["a", "b", "c"],
        ["d", "e", "f"],
        ["g", "h", "i"]
    ],
    "data": [
        [1, 2, 3],
        [2, 3, 4],
        [4, 5, 6]
    ]
}

答案 1 :(得分:1)

您只需将其添加到空dict中:

data = [[1,2,3], [2,3,4], [4,5,6]]
a = {}
a.update({"data":data})
print a

#{'data': [[1, 2, 3], [2, 3, 4], [4, 5, 6]]}

你在第一种风格中尝试的只是一种dict格式。从该字典中获取精确的json您可以将此dict添加到json.dump以转储该文件。

对于json格式,您只需将其转储为:

import json
b = json.dumps(a)
print b
#{"data": [[1, 2, 3], [2, 3, 4], [4, 5, 6]]}

您可以访问pro.jsonlint.com并检查json格式是否正确。