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
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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.