0

I created an object looks like this:

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. If a create a new Rectangle and call tojson() I get the object in the format I need.

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.

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!

4
  • 4
    What is your issue? Is it just the json formating? the json generated for the list is good for a json synatx point of view? Commented Apr 30, 2020 at 11:34
  • Yes my issue is just the formatting, the syntax is good. Commented Apr 30, 2020 at 11:39
  • 1
    Try print(json.dumps(rects, default = lambda x: x.__dict__), indent=4) Commented Apr 30, 2020 at 11:42
  • Thank you all for the help! Commented Apr 30, 2020 at 11:45

1 Answer 1

1

You can use the indent and sort_keys values:

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

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

You're already doing that in your first example but not in your second.

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I used it in the object, but forgot using in case of list. :) Helped me a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.