Home > Software engineering >  How to convert Django TextField string into JSON?
How to convert Django TextField string into JSON?

Time:08-07

I have the following model:

class Car(models.Model):
    data = models.TextField(default="[]")

Also, I have the following serializer:

class CarSerializer(serializers.ModelSerializer):
    data = serializers.ListField(child=serializers.CharField())

The REST API gets data and saves it as text field. In my to_dict method of Car, I want to convert self.data into JSON and return the dict:

def to_dict(self):
    result = dict()
    result['data']= json.loads(self.data)
    return result

But it fails with the error:

json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)

As I understand, the reason is that self.data is:

"['a', 'b', 'c']"

And not:

'["a", "b", "c"]'

I'm familiar with JsonField, but since I'm using SQLite without JSON1 externation, I can't use it. How can I convert self.data to JSON?

CodePudding user response:

You can use python json.dumps() method to convert string into json format and then use json.loads() to convert json into python object.

import json

def to_dict(self):
    result = dict()
    data = json.dumps(self.data)
    result['data'] = json.loads(data)
    return result

CodePudding user response:

The simplest way to solve this problem is json.loads(self.data.replace('\'','\"')).

Replace ' to ".

Or you can try eval(self.data)

you can watch a sample here about the usage of eval

  • Related