0

I'm using flask and my backend returns to AJAX a response in the form of a python list, and then JavaScript understands it as a string, but that's a problem because I have to iterate over that list.

All i could find on the internet is how to check the type of a variable, but couldn't find any method (which in python is pretty straightforward) to change it

9
  • 1
    Try JSON.parse. Commented Aug 29, 2019 at 2:40
  • Array.isArray() to check for array..typeof keyword to know the type of variable Commented Aug 29, 2019 at 2:42
  • But the variable is a string @ShivendraGupta - so Array.isArray and typeof return false and "string" respectively. Commented Aug 29, 2019 at 2:44
  • Most of the times HTTP response are coming like a string. So you can do two things. First, you have to check it is that data are string type? if so convert them into an object. typeof response === 'string' then JSON.parse( response ) Commented Aug 29, 2019 at 2:45
  • Possible duplicate of Parse JSON string into an array Commented Aug 29, 2019 at 2:46

2 Answers 2

0

The Array.isArray() method determines whether the passed value is an Array or not.

var someNumbers = [1,2,3];
console.log( Array.isArray( someNumbers ) );

and if it is an array it will return

true

Check this link to know more about Array.isArray

Sign up to request clarification or add additional context in comments.

1 Comment

That's not the question that's being asked; OP knows that JavaScript is working with a string, but s/he wants to force his JavaScript to understand it's really an array.
0

If your response is a string, you can use JSON.parse to turn it into an JS Object/Array.

var response = someAjaxStuff(...);
// response is a string
response = JSON.parse(response);
// now reponse is an Object/Array

If you use AJAX with jQuery, you can also use dataType:

$.ajax({
    url: 'https://example.com/api/somejson',
    dataType: 'json',
    method: 'get',
    success: function(res) {
        // console.log res will be an object/array here.
    }

});

But if you're writing your own API, I suggest you have to add the right header to tell browser that it is a JSON format instead of string.

For flask you can use jsonify (reference):

return jsonify(somedict)

4 Comments

i'm trying the first option you presented, and i get the console error: "Uncaught SyntaxError: Unexpected token u in JSON at position 2"
Maybe your string is not a valid JSON. You can validate your string here.
my string is actually a python list [[a,b,c],[d,e,f],...]
If that's not a JSON, it's impossible for JS to read that string (unless you write a parser for that). Make sure your API can response a valid JSON.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.