[英]How to tell JavaScript that my variable is an array and not a string?
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. 我使用的是flask,我的后端以python列表的形式将响应返回给AJAX,然后JavaScript将其理解为字符串,但这是一个问题,因为我必须遍历该列表。
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 我在互联网上能找到的就是如何检查变量的类型,但是找不到任何方法(在python中非常简单)来更改它
If your response is a string, you can use JSON.parse
to turn it into an JS Object/Array. 如果您的响应是字符串,则可以使用
JSON.parse
将其转换为JS对象/数组。
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与jQuery结合使用,则还可以使用
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. 但是,如果您要编写自己的API,建议您添加正确的标头以告诉浏览器它是JSON格式而不是字符串。
For flask you can use jsonify
( reference ): 对于flask,可以使用
jsonify
( 参考 ):
return jsonify(somedict)
The Array.isArray()
method determines whether the passed value is an Array or not. Array.isArray()
方法确定传递的值是否为Array。
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 检查此链接以了解有关Array.isArray的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.