栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将二维列表写入JSON文件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将二维列表写入JSON文件

我认为您可以使用我对另一个类似问题的答案来做您想要的事情。当与之搭配使用时

json.dumps()
,您指出并非由于某种原因
json.dump()

在调查此事之后,我发现在链接的答案中被覆盖

enpre()
的派生方法
json.JSONEnprer
仅在
dumps()
被调用时才被调用,而在何时
dump()
被调用时才被调用。

幸运的是,我很快就能够确定在两种情况下都 确实 调用了该

iterenpre()
方法,因此能够通过或多或少地只是将代码移至另一个方法中而解决该问题。
__
enpre()

紧接在下面的代码是修订版,其中有此更改:

__我对其他问题的回答中的代码的 修改 版本:

from _ctypes import PyObj_FromPtr  # see https://stackoverflow.com/a/15012814/355230import jsonimport reclass 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 = valueclass MyEnprer(json.JSONEnprer):    FORMAT_SPEC = '@@{}@@'  # Unique string pattern of NoIndent object ids.    regex = re.compile(FORMAT_SPEC.format(r'(d+)'))  # compile(r'@@(d+)@@')    def __init__(self, **kwargs):        # Keyword arguments to ignore when encoding NoIndent wrapped values.        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(MyEnprer, self).__init__(**kwargs)    def default(self, obj):        return (self.FORMAT_SPEC.format(id(obj)) if isinstance(obj, NoIndent)         else super(MyEnprer, self).default(obj))    def iterenpre(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 enpred in super(MyEnprer, self).iterenpre(obj, **kwargs): match = self.regex.search(enpred) 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.     enpred = enpred.replace(      '"{}"'.format(format_spec.format(id)), json_repr) yield enpred

将其应用于您的问题:

# 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=MyEnprer, sort_keys=True, indent=4))# test custom JSonEnprer with json.dump()with open('data_struct.json', 'w') as fp:    json.dump(data_struct, fp, cls=MyEnprer, 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]    ]}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616873.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号