44

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
Vandal
  • 903
  • 1
  • 14
  • 27
rak1n
  • 671
  • 1
  • 8
  • 17
  • there's no assignments in JSON, just the data to the right of `=`, and it looks like the JSON should have `"` instead of `'` on the items, and not be over-all quoted. – dandavis Dec 30 '16 at 21:21
  • Is `services` in your post a variable or part of the item you received? – Wais Kamal Dec 30 '16 at 21:22
  • its what i receive from my call. i am storing it as services = JSONField(blank=True, default=list) in my models. I will try the quote trick, think that might be the parse issue. – rak1n Dec 30 '16 at 21:27
  • Don't try to create JSON using your own code. Use `json.dumps()`. – Barmar Dec 30 '16 at 21:41

7 Answers7

76

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

This should work:

services = '["service1", "service2", "service3"]'
JSON.parse(services)
Erick R Soto
  • 1,331
  • 9
  • 6
12

This is used to convert string which is array into pure array

var a = '[Aakash,akash]'
a.replace(/\[|\]/g,'').split(',')
(2) ["Aakash", "akash"]
Aakash Handa
  • 1,215
  • 11
  • 18
11

Your response is of the form

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

JSON.parse() will work if the parent quote is a single quote and all other child quotes are double quotes. I have quoted an example below

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

We can use replace() to achieve this Here is a working example

services = "['service1', 'service2', 'service3']"
services = services.replace(/'/g, '"') //replacing all ' with "
services = JSON.parse(services)
console.log(services)
kannan
  • 136
  • 1
  • 3
  • 1
    Also, if you have trailing comma in your array, make sure to remove it or error will be thrown: `.replace(/,]$/, ']')` – iamkirill Nov 10 '22 at 17:58
3

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.

l_degaray
  • 63
  • 9
2

Try Using:

var services = "['service1', 'service2', 'service3']"
services = services .split(",");
services [0] = services [0].substring(1);
services [services .length - 1] = services [services .length - 1].substring(
  0,
  services [services .length - 1].length - 1
);
services .forEach((x, i) => {
  services [i] = services [i].includes('"') ? services [i].replaceAll('"', "").trim()
     : services [i].replaceAll("'", "").trim();
});

console.log(services );
Msk Satheesh
  • 1,398
  • 1
  • 6
  • 7
1

Just follow these steps

  1. let arr = new Array(services);
  2. let servicesArray = JSON.parse(arr[0]);

By these two steps you array "['service1', 'service2', 'service3']" would be converted to this one ['service1', 'service2', 'service3']

Ankit Pandey
  • 106
  • 4
0

I recently found a roundabout way of solving a similar problem. I wanted to store an array as a data attribute in an HTML element so that I could use it later in the JS. However, such an HTML attribute could only be stored as a string. To solve this...

  1. First I turned the arrays into a single string, with each value separated by a comma (ex. ["test 1", "test 2", "test 3"] is written as “test 1,test 2,test 3”).
  2. Next, I entered the new string into the desired HTML data attribute. (ex. <div data-somedata="test 1,test 2,test 3"></div>)
  3. Upon entering the JS, I retrieved that data string and converted it back into an array by using jQuery's "split” method. For this check out the snippet here.

let stillString = $("[data-something]").attr('data-something');
console.log(stillString);

let nowArray = stillString.split(",");
console.log(nowArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<div data-something="test 1,test 2,test 3"></div>

This may not look pretty, keeping an array as a string, but it gets the job done and your average users won't know the difference.

NOTE: You don't HAVE to use commas. You could use any character really. The only thing that matters that none of the values that you're trying to separate contain the character that you chose split them with.

Rage6
  • 13
  • 5