【问题标题】:Loop through a json file in correct order以正确的顺序循环一个 json 文件
【发布时间】:2014-12-16 18:27:37
【问题描述】:

我正在尝试循环访问一个 json 文件以创建上一页和下一页。

我的意思是:

<a href="Link to next page">Next</a>
<a href="Link to previous page">Previous</a>

需要一个产品链接来代替href。此链接位于 JSON 文件中。

{
    "collection": {
        "9409555": {
            "id": 9409555,
            "url": "lola-dress-9409555.html"
        },
        "9806609": {
            "id": 9806609,
            "url": "kimono-dress.html",
        }, //and 20 product more...

我正在苦苦思索实现这一目标的最佳方法是什么。如何确定我在循环中的哪个“位置”以及如何确定下一个或上一个值是什么。

脚本

 $.getJSON('link-to-json-file/?format=json', function(data){
        $.each(data.products, function(key, product){
          console.log(key, product);
        });
      });

我知道我可以像上面那样循环遍历一个 json 对象。任何人都可以给我一些指示什么是好的方法。欢迎任何帮助!

【问题讨论】:

  • 我编辑了你的对象文字。我只插入了空格——它看起来并不完整,现在可以很容易地看到。如果您正在寻找哈希或对象内的位置信息 - 这是不可能的,没有保证的顺序。

标签: jquery json


【解决方案1】:

根据您的 JSON 结构,您可以这样做:

  $.getJSON('link-to-json-file/?format=json', function(data){
    var pos = 0;
    for(var key in data.collection){
       console.log(pos);           
       console.log(key);
       console.log(data.collection[key].id);
       console.log(data.collection[key].url);
       pos++;
    });
  });

如果您的 JSON 具有数组结构,那么您可以使用 $.each

{
    "collection": [
        {
            "id": 9409555,
            "url": "lola-dress-9409555.html"
        },
        {
            "id": 9806609,
            "url": "kimono-dress.html",
        }
     ]
}

  $.getJSON('link-to-json-file/?format=json', function(data){
    $.each(data.callection, function(index, product){
      console.log(index); //this is the position 0, 1, 2 ...
      console.log(product);
    });
  });

【讨论】:

  • 请注意:虽然jQuery.each 也接受对象[...]If an object is used as the collection, the callback is passed a key-value pair each time[...],但对象应该包含length 属性然后[...], if the collection has a property called length [...] the function might not work as expected.[...]
  • $.each(object, callback) 的回调是 function(propertyName, value){} 而不是 function(index, value){},因为它是用于数组的。此外,大多数浏览器将按字母顺序返回属性,而不是它们在代码中声明的顺序。
  • 没错,但是我们如何使用每个 with 和 object 来知道位置呢?
  • for ... in 一样:var pos = 0; $.each(data.collection, function(propertyName, value){ pos++; });。不要误会我的意思,因为length 问题,我不想建议$.each 用于对象。这只是文档的摘要,因为 OP 使用 $.each 和一个对象。
【解决方案2】:

这感觉真的很hacky,但我能想到的唯一方法是循环遍历对象,并在原始responseText中找到产品属性的索引(例如"9806609": {)。

这非常假设它是以您发布它的方式形成的,并且responseText 中没有其他文本可以匹配。您可以通过去掉冒号前后的新行和空格等来使其更安全。

// will store the final products
var products = [];

$.getJSON('link-to-json-file/?format=json', {}, function (data, textStatus, jqXhr) {
    // loop through object, adding the ID, product and position of "pid": in the jqXhr.responseText
    var sortProducts = [];
    $.each(data.collection, function(key, product){
        sortProducts.push({
            pid: key,
            product: product,
            pos: jqXhr.responseText.indexOf('"'+key+'":')
        });
    });

    // now sort the products by their position and store in the final array
    products = sortProducts.sort(function(a,b) {
        return a.pos - b.pos;
    });
});

您可以使用简单的数组搜索找到索引:

function findProductIndex(pid) {
    var prodIndex = -1;
    for(var i = 0; i < products.length; i++) {
        if(products[i].pid == pid) {
            return i;
        }
    }
}

var idx = findProductIndex('9806609');

当然,如果顺序对您很重要,将collection 创建为数组是可行的方法,您将立即获得排序后的数组:

"collection": [
    {
        "id": 9409555,
        "url": "lola-dress-9409555.html"
    },
    {
        "id": 9806609,
        "url": "kimono-dress.html",
    }
]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-26
    相关资源
    最近更新 更多