json自定义缩进,list不换行——python(满足强迫症患者需要)

copy from:https://stackoverflow.com/questions/13249415/how-to-implement-custom-indentation-when-pretty-printing-with-the-json-module

效果:

{
  "5131": [
    {
      "path_p": ["j2690", "j2701"],
      "path_t": 123456789
    },
    {
      "path_p": ["j2690", "j2701"],
      "path_t": 987654321
    }
  ],
  "7286": [
    {
      "path_p": ["j2690", "j2701"],
      "path_t": 123456789
    },
    {
      "path_p": ["j2690", "j2701"],
      "path_t": 987654321
    }
  ]
}

代码:

from _ctypes import PyObj_FromPtr
import json
import re

class NoIndent(object):
    """ Value wrapper. """
    def __init__(self, value):
        self.value = value


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

    def __init__(self, **kwargs):
        # Save copy of any keyword argument values needed for use here.
        self.__sort_keys = kwargs.get('sort_keys', None)
        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 encode(self, obj):
        format_spec = self.FORMAT_SPEC  # Local var to expedite access.
        json_repr = super(MyEncoder, self).encode(obj)  # Default JSON.

        # Replace any marked-up object ids in the JSON repr with the
        # value returned from the json.dumps() of the corresponding
        # wrapped Python object.
        for match in self.regex.finditer(json_repr):
            # see https://stackoverflow.com/a/15012814/355230
            id = int(match.group(1))
            no_indent = PyObj_FromPtr(id)
            json_obj_repr = json.dumps(no_indent.value, sort_keys=self.__sort_keys)

            # Replace the matched id string with json formatted representation
            # of the corresponding Python object.
            json_repr = json_repr.replace(
                            '"{}"'.format(format_spec.format(id)), json_obj_repr)

        return json_repr

#input json file
json_data = {}
grid_list = [["j2690", "j2701"], ["j2690", "j2701"]]
time_list = [123456789, 987654321]
for did in ["7286", "5131"]:
    path_list = []
    for i in range(len(grid_list)):
        path_list.append({"path_t":time_list[i], "path_p":NoIndent(grid_list[i])})
    print(path_list)
    json_data[did] = path_list
    
with open('path.json', 'w') as fw:
    # 整理格式,list部分不换行
    json_data = json.dumps(json_data, cls=MyEncoder, ensure_ascii=False, sort_keys=True, indent=2)
    fw.write(json_data)
    fw.write('\n')
    
  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值