简体   繁体   English

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);
                });
            });
        });

Here is my javacript code. 这是我的javacript代码。 I want to push json object's all values with key as topic. 我想以键为主题推送json对象的所有值。 But when I try to access test[i] (i be any integer within array length) I get an error "undefined" . 但是,当我尝试访问test [i](我是数组长度内的任何整数)时,出现错误“ undefined”。 What' am I msissing? 我在想什么?

Here is my json object sample- 这是我的json对象样本-

[
        {
            "topic": "Books",
            "quantity": 3
        },
        {
            "topic": "Grossery",
            "quantity": 3
        },
        {
            "topic": "stationery",
            "quantity": 3
        },
        {
            "topic": "food",
            "quantity": 2
        },
        {
            "topic": "market items",
            "quantity": 3
        }
]

See the following working code: 请参阅以下工作代码:

 var data = [ { "topic": "Books", "quantity": 3 }, { "topic": "Grossery", "quantity": 3 }, { "topic": "stationery", "quantity": 3 }, { "topic": "food", "quantity": 2 }, { "topic": "market items", "quantity": 3 } ] var test = []; $.each(data,(i,v) => test.push(v.topic)); console.log(test); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> 

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? 您是否正在执行传递给getJson的回调之前访问数据?

Here's an example that works if I serve it locally using python3 -m http.server 8080 : 这是一个示例示例,如果我使用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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM