Json数据转换为javascript数组(Json data into javascript array)

编程入门 行业动态 更新时间:2024-10-10 10:31:44
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>

更多推荐

本文发布于:2023-08-07 12:12:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464322.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   数据   Json   array

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!