Reputation: 10956
I want to convert database result set into json.
I used json.dumps()
it converts as "{key:\"value\"}"
but I don't want quotes around the string and backlashes. How I can convert as {key:"value"}
Here is my code.
Model
class DeviceDetail(models.Model):
deviceId = models.CharField(max_length=200)
payload = models.CharField(max_length=2000)
View
data = json.dumps(list(DeviceDetail.objects.filter(deviceId=deviceId).values('deviceId','payload')))
HttpResponse(data)
Response:
[
{
"deviceId":"10",
"payload":"{key:\"value\"}"
},
{
"deviceId":"10",
"payload":"{key:\"value\"}"
},
{
"deviceId":"10",
"payload":"\"{key:\\\"value\\\"}\""
},
{
"deviceId":"10",
"payload":"{key:\"value\"}"
}
]
Without json.dumps()
{'deviceId': u'10', 'payload': u'{key:"value"}'}
Upvotes: 0
Views: 3849
Reputation: 1125238
Your payload
values are encoded strings and these are encoded as JSON strings again.
If you wanted those to be JSON objects instead, you'll first have to decode them to Python objects:
data = json.dumps([
{'deviceId': dd['deviceId'], 'payload': json.loads(dd['payload'])}
for dd in DeviceDetail.objects.filter(deviceId=deviceId).values('deviceId','payload')
])
where I assume that the values are actual JSON-encoded values.
If they are not JSON encoded values, then it is unclear what you want. As strings, the JSON encoding for them is entirely correct and quotes in the values must be escaped using backslashes.
Upvotes: 2