jquery - 使用 jQuery 循环 JSON 文件

标签 jquery json

我试图循环遍历这个 JSON 字符串(位于一个名为 language.json 的单独 json 文件中),但没有任何效果

{
    "language": [
    {
        "name": "English Languages",
        "values": ["English 1", "English 2", "English 3", "English 4"]
    },
    {
        "name": "French Languages",
        "values": ["French 1", "French 2", "French 3", "French 4"]
    },
    {
        "name": "Spanish Languages",
        "values": ["Spanish 1", "Spanish 2", "Spanish 3", "Spanish 4"]
    }
    ]}

jQuery

$.getJSON("script/countries.json", function (data) {  
     $.each(data.language, function (i, v) {
     var category = data[i];
     console.log(category.name)
     $.each(category.values, function (i, v){
         console.log(category.values[i])
     });
 });

有人可以帮我吗?我想打印语言名称,然后打印它的值列表。

输出:

English Language:
English1
English2..
French Language
French1
French2

等等 谢谢!

最佳答案

假设您的回调被调用并且数据具有所需的值。

data[i] 将返回 undefined,因为您正在迭代 data.language,因此您需要使用 varcategory = data.language[i] $.each()会将当前值作为第二个参数传递给回调。所以你可以

//this will iterate through the data.language list and for each item in the array the callback method will be called. 
//The callback method will receive the index of the current item and the item as its 2 parameters
$.each(data.language, function (i, category) {
    //here category is the current item in the data.language array so it has the name and values properties
    console.log(category.name)
    //the same logic follows here, we are iterating through the values array and since it is an array of string calues the second param lang will be the language
    $.each(category.values, function (i, lang) {
        console.log(lang)
    });
});

关于jquery - 使用 jQuery 循环 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26008452/

相关文章:

php - jQuery 远程验证帮助

jquery - 如何在 data() 对象中存储表单值?

javascript - 如何从现有 JSON 文件添加新 JSON

javascript - 将 HTML 内容作为属性动态传递给 Angular 指令

javascript - 如何从 JSONP 语句中选择变量

javascript - 当 AJAX 响应来自 PHP 文件时,如何在中心显示带有消息的加载器图像并防止引导模式对话框关闭?

javascript - 如何从 Facebook API 返回的 jsonp 中获取数据作为封面图片

java - Json格式错误显示

java - 如何使用 jettison 从 Java 中的 Json 对象获取正确格式的日期

javascript - 如何使用javascript通过类名更改html元素的值