JSON dumps custom formatting

后端 未结 3 1676
情深已故
情深已故 2020-12-03 16:56

I\'d like to dump a Python dictionary into a JSON file with a particular custom format. For example, the following dictionary my_dict,

\'text_li         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-03 17:39

    Here's something that I hacked together. Not very pretty but it seems to work. You could probably handle simple dictionaries in a similar way.

    class MyJSONEncoder(json.JSONEncoder):
        def __init__(self, *args, **kwargs):
            super(MyJSONEncoder, self).__init__(*args, **kwargs)
            self.current_indent = 0
            self.current_indent_str = ""
    
        def encode(self, o):
            #Special Processing for lists
            if isinstance(o, (list, tuple)):
                primitives_only = True
                for item in o:
                    if isinstance(item, (list, tuple, dict)):
                        primitives_only = False
                        break
                output = []
                if primitives_only:
                    for item in o:
                        output.append(json.dumps(item))
                    return "[ " + ", ".join(output) + " ]"
                else:
                    self.current_indent += self.indent
                    self.current_indent_str = "".join( [ " " for x in range(self.current_indent) ])
                    for item in o:
                        output.append(self.current_indent_str + self.encode(item))
                    self.current_indent -= self.indent
                    self.current_indent_str = "".join( [ " " for x in range(self.current_indent) ])
                    return "[\n" + ",\n".join(output) + "\n" + self.current_indent_str + "]"
            elif isinstance(o, dict):
                output = []
                self.current_indent += self.indent
                self.current_indent_str = "".join( [ " " for x in range(self.current_indent) ])
                for key, value in o.items():
                    output.append(self.current_indent_str + json.dumps(key) + ": " + self.encode(value))
                self.current_indent -= self.indent
                self.current_indent_str = "".join( [ " " for x in range(self.current_indent) ])
                return "{\n" + ",\n".join(output) + "\n" + self.current_indent_str + "}"
            else:
                return json.dumps(o)
    

    NOTE: It's pretty much unnecessary in this code to be inheriting from JSONEncoder.

提交回复
热议问题