48

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
4
  • 1
    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. Commented Dec 30, 2016 at 21:21
  • Is services in your post a variable or part of the item you received? Commented Dec 30, 2016 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. Commented Dec 30, 2016 at 21:27
  • Don't try to create JSON using your own code. Use json.dumps(). Commented Dec 30, 2016 at 21:41

9 Answers 9

83

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

This should work:

services = '["service1", "service2", "service3"]'
JSON.parse(services)
Sign up to request clarification or add additional context in comments.

4 Comments

It works for me as well. Is there any intuition behind this? why the one with ' ' don't work?
Watch out for that trailing ` after the JSON.parse()
@FatemehRahimi the one with '' don't work because JSON recognize only "" for strings
I did a services.replaceAll('\'', '"') --- note 2nd one has " within the enclosing '
13

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

var a = '[Aakash,akash]'
a.replace(/\[|\]/g,'').split(',')
(2) ["Aakash", "akash"]

3 Comments

Do you mind to explain what this /\[|\]/g means ?
@Nizzam let string = "[2, 4, 5, 7]"; let array = string.replace(/[|]/g, "").split(", "); /[|]/g is a regexp to remove the "[" and "]" in the string
@Nizzam its a regular expression - \ is escape character like you said, the | means or, and /g at the end means global - a replace all. However the OP's example already has single quotes in it.
12

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)

1 Comment

Also, if you have trailing comma in your array, make sure to remove it or error will be thrown: .replace(/,]$/, ']')
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.

Comments

3

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 );

Comments

1

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.

Comments

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']

Comments

0
var services = "['service1', 'service2', 'service3']";

// --- You can use JavaScript Default function for that
var dataArray = JSON.parse(services.replace(/'/g, '"')); 
// --- .replace(/'/g, '"') we use this to convert double quotes to single because in JSON we use double Quotes

dataArray.forEach(service => {
    console.log(service);
});

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

eval

Warning: SUPER DANGEROUS. Don't pass unsanitized input.

> services = "['service1', 'service2', 'service3']"
> eval(services)

Array(3) [ "service1", "service2", "service3" ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.