I
I
iFortunes2018-04-17 10:33:32
Python
iFortunes, 2018-04-17 10:33:32

How to write to the database in json format certain indexes and values ​​from a list in python?

The essence of the question is as follows,
in php it is enough just to write such an array:
$data = [
'0' => 1,
'4' => 2,
'7' => 3
];
json_encode($data); and write to the database.
How can you write the same format only in python? That is, preserving the order of the array keys.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rostislav Grigoriev, 2018-04-17
@iFortunes

I believe that it is not enough to write to the database even in php $data = ['0'=>1, '4'=>2]
In python, it is done something like this:

import json

data = {'0': 1, '4': 2}
instance.field_name = json.dumps(data)
instance.save()

You can also use a JSONField field , then reading/writing json will be transparent:
from django.contrib.postgres.fields import JSONField
from django.db import models

class CustomModel(models.Model):
    json_field_name = JSONField()

instance = CustomModel()
instance.field_name = {'0': 1, '4': 2}
instance.save()

You can only preserve the order of the keys if you use an OrderedDict , however this does not guarantee that the order will be preserved when saved to JSON and read. It is better to slightly change the data format for such purposes, for example, use a list:
data = [{'0': 4}, {'4': 2}]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question