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
The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.
To convert an array of strings to an array of numbers:Use the forEach() method to iterate over the strings array. On each iteration, convert the string to a number and push it to the numbers array.
The split() method splits a string into an array of substrings. The split() method returns the new array.
To parse it you need to use double quotes instead of single.
This should work:
services = '["service1", "service2", "service3"]' JSON.parse(services)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With