I get the following item back from my django-rest-framework api call:
我从我的django-rest-framework api调用中得到以下项目:
services = "['service1', 'service2', 'service3']"
I want services = ['service1', 'service2', 'service3']
我想要服务= ['service1','service2','service3']
In my JavaScript I tried services = JSON.parse(services)
- didn't do anything, also tried $.parseJSON(services)
.
在我的JavaScript中,我尝试了services = JSON.parse(services) - 没有做任何事情,也尝试了$ .parseJSON(服务)。
In my serializers I have tried the setting services as ListField
, also tried JSONSerializerField()
在我的序列化程序中,我尝试将设置服务作为ListField,也尝试了JSONSerializerField()
class JSONSerializerField(serializers.Field):
# Adapted from http://*.com/a/28200902
def to_internal_value(self, data):
return json.loads(data)
def to_representation(self, value):
return value
2 个解决方案
#1
1
To ensure correct parsing between Django and some javascript browser code, be sure that you return a JsonResponse() in your controller. This ensures you can parse it with JSON.parse() in your Javascript.
为了确保Django和某些javascript浏览器代码之间的正确解析,请确保在控制器中返回JsonResponse()。这可以确保您可以使用Javascript中的JSON.parse()来解析它。
#2
0
You need to use double quote instead of single.
您需要使用双引号而不是单引号。
This should work:
这应该工作:
services = '["service1", "service2", "service3"]'
JSON.parse(services)`
#1
1
To ensure correct parsing between Django and some javascript browser code, be sure that you return a JsonResponse() in your controller. This ensures you can parse it with JSON.parse() in your Javascript.
为了确保Django和某些javascript浏览器代码之间的正确解析,请确保在控制器中返回JsonResponse()。这可以确保您可以使用Javascript中的JSON.parse()来解析它。
#2
0
You need to use double quote instead of single.
您需要使用双引号而不是单引号。
This should work:
这应该工作:
services = '["service1", "service2", "service3"]'
JSON.parse(services)`