Json数据转换为javascript数组(Json data into javascript array)
var test=[];
$(document).ready(function(){
$.getJSON("data.json",function(data){
$.each(data,function(key,value){
test.push(value.topic);
});
});
});
这是我的javacript代码。 我想用键作为主题推送json对象的所有值。 但是当我尝试访问test [i](我是数组长度内的任何整数)时,出现“undefined”错误。 我有什么困难?
这是我的json对象sample-
[ { "topic": "Books", "quantity": 3 }, { "topic": "Grossery", "quantity": 3 }, { "topic": "stationery", "quantity": 3 }, { "topic": "food", "quantity": 2 }, { "topic": "market items", "quantity": 3 } ] var test=[]; $(document).ready(function(){ $.getJSON("data.json",function(data){ $.each(data,function(key,value){ test.push(value.topic); }); }); });Here is my javacript code. I want to push json object's all values with key as topic. But when I try to access test[i] (i be any integer within array length) I get an error "undefined" . What' am I msissing?
Here is my json object sample-
[ { "topic": "Books", "quantity": 3 }, { "topic": "Grossery", "quantity": 3 }, { "topic": "stationery", "quantity": 3 }, { "topic": "food", "quantity": 2 }, { "topic": "market items", "quantity": 3 } ]最满意答案
你的代码似乎对我来说工作得很好。
在你传递给getJson的回调被执行之前,你是否正在访问数据?
这里有一个例子,如果我使用python3 -m http.server 8080在本地提供服务,
<html> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var test=[]; $(document).ready(function(){ $.getJSON("data.json",function(data){ $.each(data,function(key,value){ test.push(value.topic); }); // only use test array after data has been loaded doWork(); }); }); function doWork() { $('#output').text( test + ' ' + test[0] ); } </script> </head> <body> <div id="output"></div> </body> </html>Your code seems to be working fine for me.
Are you accessing the data before the callback that you pass to getJson has been executed?
Here's an example that works if I serve it locally using python3 -m http.server 8080:
<html> <head> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> var test=[]; $(document).ready(function(){ $.getJSON("data.json",function(data){ $.each(data,function(key,value){ test.push(value.topic); }); // only use test array after data has been loaded doWork(); }); }); function doWork() { $('#output').text( test + ' ' + test[0] ); } </script> </head> <body> <div id="output"></div> </body> </html>更多推荐
发布评论