Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string array to array in javascript

Tags:

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 
like image 872
rak1n Avatar asked Dec 30 '16 21:12

rak1n


People also ask

How do I convert a string to an array in JavaScript?

The string in JavaScript can be converted into a character array by using the split() and Array. from() functions.

How do you turn an array of strings into numbers?

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.

Which of the following method is used to convert a string into an array in JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array.


2 Answers

To parse it you need to use double quotes instead of single.

This should work:

services = '["service1", "service2", "service3"]' JSON.parse(services) 
like image 93
Erick R Soto Avatar answered Sep 21 '22 18:09

Erick R Soto


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.

like image 41
l_degaray Avatar answered Sep 20 '22 18:09

l_degaray