0

I am using mongodb with django and want to store json object in mongodb. Here is my code

Model

class Data(models.Model):
    deviceId = models.CharField(max_length=200)
    payload = models.CharField(max_length=2000)

View save data

deviceId = request.POST.get('deviceId')
payload = request.POST.get('payload')
data = Data.objects.create(deviceId=deviceId, payload=payload);
data.save()

View fetch data

data = json.dumps(list(Data.objects.all().values('deviceId','payload')))

Response

{
  "data":{
   "payloads":"{name:\"xyz\"}"
  "id":"xxxxx"
  },
}

The problem is with "payloads":"{name:\"xyz\"}". Here is a string instead of json Object.

I want "payloads":"{name:"xyz"}". How can convert this into json object in django. Is there anyway to convert all of the dataset into json object instead of iterating each object from dataset

2 Answers 2

1

I think you should be able to just remove the json.dumps part of the script. That's a python command to translate a valid JSON object into a string!

data = list(Data.objects.all().values('deviceId','payload'))
Sign up to request clarification or add additional context in comments.

1 Comment

No, Actually it returns a list and I want response in json
0

To store JSON I recommended to use JSONField.

from jsonfield import JSONField
class Data(models.Model):
    deviceId = models.CharField(max_length=200)
    payload = models.JSONField(max_length=2000)

Comments

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.