Convert string array to array in javascript

2020-04-07 19:53发布

问题:

I get the following item back from my django-rest-framework api call:

services = "['service1', 'service2', 'service3']"

I want services = ['service1', 'service2', 'service3']

In my JavaScript I tried services = JSON.parse(services) - didn't do anything, also tried $.parseJSON(services).

In my serializers I have tried the setting services as ListField, also tried JSONSerializerField()

class JSONSerializerField(serializers.Field):
    # Adapted from http://stackoverflow.com/a/28200902
    def to_internal_value(self, data):
        return json.loads(data)

    def to_representation(self, value):
        return value

回答1:

You need to use double quote instead of single.

This should work:

services = '["service1", "service2", "service3"]'
JSON.parse(services)`


回答2:

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.