whitebear
whitebear

Reputation: 12423

Keep order of json in JSONField in DB

I have model which has JSONField.

class UserData(models.Model):
    detail = JSONField()

then I input the data like this.

json = {
     "name":"melody",
     "status":"good",
     "method":'hard'
}

u = Userdata(detail=json)
u.save()

However the order of items are not kept. I want to keep the order name, status,method

Is there any way to keep the order of json items??

$python -V
Python 3.7.9

Upvotes: 0

Views: 413

Answers (1)

HymnZzy
HymnZzy

Reputation: 2925

Convert it to a string or into an array with elements with "field" and "value" keys (see example below). That's the only way to keep the order. JSON is not designed to have a fixed order of key/value pairs.

[
   {field:"name",value:"melody"},
   {field:"status",value:"good"},
   {field:"method",value:'hard'}
]

Upvotes: 2

Related Questions