Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove backslashes from Json String in Django Rest Framework

dct_data = json_tour_data.__dict__
tour_data = json.dumps(dct_data)

How to remove these backslashes from json? Here is my output:

"{\"strFileOpenDateAjxKey\": \"2018-01-16 12:40:22.526417\", 
\"strFilePassengerAjxKey\": \"Zahra Walji\", \"strFileOpenMobileAjxKey\": 
\"46464664\", \"strFileOpenDepartmentAjxKey\": \"Finance department\", 
\"strFileOpenAccountCodeAjxKey\": \"CARTZS\", 
\"strFileOpenProfileCodeAjxKey\": \"CARTZS\", 
\"strFileopenOriginalCountryIdAjxKey\": 61, \"blnBoundAjxKey\": 1, 
\"strTransactionCurrencyJsKey\": \"Shillings\", 
\"intCurrencyPrecisionJsKey\": 3, \"strPackageTypeJsKey\": \"PKG\", 
\"strUserNameAjxKey\": \"admin\", \"strPasswordAjxKey\": \"1234\"}"
like image 379
Jamshy Avatar asked Jun 03 '26 15:06

Jamshy


2 Answers

The answer is you have to just play with json.dumps() and json.loads().

The following is my code which worked:-

import json
json_data = {'key1': 'first'}
json_data = json.dumps(json_data)
return {
    'statusCode': 200,
    'schools':  json.loads(json_data)
}

The output of above code is as follows:

Response:
{
  "schools": {
    "key1": "first"
  },
  "statusCode": 200
}
like image 57
Rushabh Sudame Avatar answered Jun 06 '26 04:06

Rushabh Sudame


I would recommend checking your Response object where your parse your tour_data variable/dictionary in your views. I originally had the same issue as you but here's what I changed.

Original implementation: Response(json.dumps(a_dictionary), status=status.HTTP_200_OK)

to

New implementation: Response(a_dictionary, status=status.HTTP_200_OK, content_type='json')

The key things here are: 1. Getting rid of the json.dumps conversion method and just pass through a plain python dictionary e.g. see a_dictionary. 2. Setting content_type='json' on the Response object.

like image 35
Todd Drinkwater Avatar answered Jun 06 '26 03:06

Todd Drinkwater



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!