简体   繁体   English

如何从 python 中的 object 创建正确的 JSON?

[英]How to create correct JSON from an object in python?

I created an object looks like this:我创建了一个 object,如下所示:

class Rectangle:
    def __init__(self, ymin, xmin, ymax, xmax):
        self.y_min = ymin
        self.x_min = xmin
        self.y_max = ymax
        self.x_max = xmax

    def tojson(self):
        return json.dumps(self, default=lambda o: o.__dict__,
                          sort_keys=False, indent=4)

I have a more complex object but it is enought to explain.我有一个更复杂的 object 但足以解释。 If a create a new Rectangle and call tojson() I get the object in the format I need.如果创建一个新的 Rectangle 并调用 tojson(),我会得到所需格式的 object。

rect1 = Rect(1,2,3,4)
print(rect.tojson())

result:

{
    "y_min": 1,
    "x_min": 2,
    "y_max": 3,
    "x_max": 4
}

But if I have Rectangle list and I want to create a JSON, I get them in one row.但是,如果我有 Rectangle 列表并且我想创建一个 JSON,我将它们排成一行。

rects = [rect1, rect2]
print(json.dumps(rects, default = lambda x: x.__dict__))

result:
[{"y_min": 1, "x_min": 2, "y_max": 3, "x_max": 4}, {"y_min": 1, "x_min": 2, "y_max": 3, "x_max": 4}]

Could you please help me, how could I do this properly?你能帮我吗,我怎么能正确地做到这一点? Thank you in advance for your help!预先感谢您的帮助!

You can use the indent and sort_keys values:您可以使用 indent 和 sort_keys 值:

print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))

https://docs.python.org/3/library/json.html https://docs.python.org/3/library/json.html

You're already doing that in your first example but not in your second.你已经在你的第一个例子中这样做了,但在你的第二个例子中没有。

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM