如何在JSON文件中定位特定对象

时间:2014-10-26 10:39:50

标签: javascript jquery arrays ajax json

以下是我的JSON文件。数组中的每个对象都属于Id。所以第一个对象是#one,第二个对象是#two。等等。我无法弄清楚如何用JavaScript编写它。如何定位对象[1]的哪个数组[1]附加到#two?另外我需要删除对象的第一行是计数行吗?谢谢!

所以要了解更多细节。我得到了一个任务,我在html和图片下面放置了图片,json文件中的每个对象(图片描述)应该在它下面。我是json和ajax的新手:(所以ids#one,#two ......只是例子。会有6个ID。每个对象一个。

[
  [
    {
    "count": "80",
    "countTxt":"Buyer logins",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"523"
    },
    {
    "count": "233",
    "countTxt":"Searches",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"628"
    },
    {
    "count": "533",
    "countTxt":"Views of our member pages",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"2,365"
    }
  ],
  [
    {
    "count": "80",
    "countTxt":"Total vists",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"412"
    },
    {
    "count": "53",
    "countTxt":"Unique visitors",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"731"
    },
    {
    "count": "1:12 min",
    "countTxt":"Total time spent on page",
    "participantsTxt":"Total for all participating member companies:",
    "participantCount":"784.2 mins"
    }
  ]
]

4 个答案:

答案 0 :(得分:1)

您有一个包含包含对象的数组的数组。他们似乎没有在任何地方拥有这些ID,并且使用#one#two等名称,分配这些ID很尴尬(您基本上必须拥有等待分配的名单列表。

一旦你有了这个清单,工作本身就相对简单了:

  1. 通过JSON.parse将JSON解析为对象图。

    var outerArray = JSON.parse(jsonText);
    
  2. 创建一个空白对象,您可以将命名对象保存为属性,如地图:

    var map = {};
    
  3. 以数组的形式输入您的ID列表:

    // This assumes no more than 99 elements
    var ids = [
        "#one", "#two", "#three", /*...and so on...*/, "#ninety-nine"
    ];
    
  4. 拥有一个以0开头的索引变量。

  5. 循环通过最外面的数组;你有lots and lots of options for how to do that,我可能会使用forEach

    outerArray.forEach(function(nestedArray) {
       // ...more code here
    });
    
  6. 在该循环中,遍历嵌套数组中的对象:

    outerArray.forEach(function(nestedArray) {
       nestedArray.forEach(function(object) {
           // ...more code here
       });
    });
    
  7. 在内部循环中,使用索引变量使用下一个可用ID将当前对象添加到地图中:

    map[ids[index++]] = object;
    
  8. 如果您确实要这样做,请从对象中删除count属性:

    delete object.count;
    
  9. 所以把它们放在一起:

    var index = 0;
    var outerArray = JSON.parse(jsonText);
    var map = {};
    var ids = [    // This assumes no more than 99 elements
        "#one", "#two", "#three", /*...and so on...*/, "#ninety-nine"
    ];
    outerArray.forEach(function(nestedArray) {
       nestedArray.forEach(function(object) {
            map[ids[index++]] = object;
            delete object.count; // Doesn't matter whether this is before or after the line above
       });
    });
    

    注意:

    • 访问具有#one等ID的对象真的很尴尬,但我认为你有理由这样做。你可以map["#one"]来获取对象。

    • 如果您 删除count财产,请不要打扰。

答案 1 :(得分:1)

首先,您可能想问问自己当前格式化数据的方式是否合适。目前,您的数据格式如下:

var jsonObject = 
[
  [{},{},{}],
  [{},{},{}]
];

如果你有一个最外面的数组,它包含两个数组,然后json数据/ javascript对象存储在这些数组中。可能不需要最外层的数组,它将简化您在没有它的情况下访问json对象内部数据的方式。因此请记住,您在此处获得的所有示例都将在您呈现时引用JSON对象。

// List off all "countTxt" objects to demonstrate how to 
// iterate over a json object that contains nested
// arrays containing data. In your example, you have two arrays
// that each contain json data.


for (var i in jsonObject) {
    for (var j in jsonObject[i]){
        console.log(jsonObject[i][j].countTxt);
    }
}

以上循环将打印出以下内容:

/*
    Unique visitors 
    Total time spent on page 
    Buyer logins 
    Searches 
    Views of our member pages 
    Total vists 
    Unique visitors 
    Total time spent on page 
*/

警告: 作为T.J. Crowder指出,使用 for..in 循环访问json数据会回来咬你,所以在生产中不建议使用这种类型的for..in循环结构(上图)代码,但它作为一个简单的演示如何使用访问符号[]从数据对象数组中获取值。要阅读一些最佳实践,您可以阅读T.J.克劳德在这个主题here上发表了深入的帖子。

如果你想要定位jsonObject中的特定项目,你可以这样做:

// Grab the second object in the data array:
var secondObjectInJsonData = jsonObject[1];
console.log(secondObjectInJsonData);
// secondObjectInJsonData -> [Object, Object, Object]

如果您想获取数据数组中的特定数据:

// Grab the second object, inside the first array of json data
var countTxtOfSecondObject = jsonObject[0][2].countTxt;
console.log(countTxtOfSecondObject);
// countTxtOfSecondObject --> "Views of our member pages"

要删除对象,可以使用delete命令

var someObject = jsonObject[1][2];
delete someObject.count;
console.log("someObject after 'count' has been deleted: ",  someObject);

Here is a JSFiddle to see all this code in action。只需在Chrome开发者工具(在Chrome浏览器中)打开控制台即可查看所有console.log()语句的输出。

答案 2 :(得分:0)

  

首先,您应该重新格式化数据,尝试使用JSON Editor Online,这会显示数据的树状视图。 Chrome扩展程序可用于此,请检查Chrome网上应用店。这是一个非常好的做法。

     

我重新格式化了您的数据并使其变得更具可读性。看一看;

[
 {
   "count": "80",
   "countTxt":"Buyer logins",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"523"
 },
 {
   "count": "233",
   "countTxt":"Searches",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"628"
 },
 {
   "count": "533",
   "countTxt":"Views of our member pages",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"2,365"
 },
 {
   "count": "80",
   "countTxt":"Total vists",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"412"
 },
 {
   "count": "53",
   "countTxt":"Unique visitors",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"731"
 },
 {
   "count": "1:12 min",
   "countTxt":"Total time spent on page",
   "participantsTxt":"Total for all participating member companies:",
   "participantCount":"784.2 mins"
  }
]
  

您可以使用jQuery.getJSON()方法访问JSON数据,并使用jQuery.each方法循环访问该对象。试试这个;

$.getJSON('data.json', function(data) {
   $.each(data, function(k) {
      console.log(data[k]);
   });
});

检查控制台(ctrl + shift + j)。    enter image description here

  1. 现在您可以轻松访问该字符串。例如; console.log('Count: ' + data[k]['count']); //显示所有计数。
  2. 希望你有所了解,你可以像这样使用JSON对象,如果我错了,请纠正我。谢谢

答案 3 :(得分:-1)

您可以访问以下属性

json[0][0]["count"]

如果要删除属性,请使用

delete json[0][0]["count"]

小提琴http://jsfiddle.net/wa99rxgL/