Nested JSON string prettyprint correctly

this might be a rather odd question and acutally has nothing to do with Rhino.
But as I want to embed a nested JSON-string in a block description, I thought it might be okay to put that here.

I have the following object:
import json

class Rhinoceros(object):

    def __init__(self):

        Length = 0
        Height = 0

Then I create the object and I wanna store a custom JSON-string, that I migth wanna read lateron. This literally can be anything and I wanna be felxible here.

When I do the following:

test = Rhinoceros()
test.Length = 1000
test.Height = 100

text = """{
    "Name": "T.",
    "Age": 20,
    "Weight": 100.0,
    "Height": 20.0

test.Data = text

print (json.dumps(test.__dict__, indent=4))

This will result in this:
“Length”: 1000,
“Height”: 100,
“Data”: “{\n “Name”: “T.”,\n “Age”: 20,\n “Weight”: 100.0,\n “Height”: 20.0\n}”

Is there any way to make this readable like in the string above?
I might do a workaround here, no question. But maybe there’s an easier way?


HI @tobias.stoltmann , why not use a dictionary?

text = {
    "Name": "T.",
    "Age": 20,
    "Weight": 100.0,
    "Height": 20.0

print(json.dumps(text,indent=1) )

@Darryl_Menezes , hi.
That’s what I acutally did and that’s where the string comes from.
When I “store” it in the other object it’s working fine.
The moment I wanna convert that object to a json-string it concatenates it that oddly.

Oh I see. You could parse the JSON string before assigning, something like this

test.Data = json.loads(text)

This question probably doesnt belong in this category though

Correct as always, @Darryl_Menezes .
And I agree with the wrong category.

1 Like