JSON多级对象

时间:2013-12-02 00:08:13

标签: javascript html json

我正在尝试从深层嵌套的JSON对象中提取频率总和。

{ "Baltimore":{
    "health": {
      "hospital": {
        "data": {"frequency": 3, "relevance": 0.7845, "sentiment": "Mixed"},
        "metadata": {
          "article1": {"author": "Tom Jones", "title": "Current Rises in Health Insurance Policies in Baltimore", "timestamp": "26-FEB-1987 15:01:01.79"},
          "article2": {"author": "Bob Jenkins", "title": "Obamacare in Hospitals", "timestamp": "06-SEP-2011 16:32:34.73"},
          "article3": {"author": "Tom Jones", "title": "Rises in Hospital Fees", "timestamp": "31-DEC-1991 01:45:59.66"}
        } 
      } 
    },
    "crime": {
      "assault": {
        "data": {"frequency": 12, "relevance": 0.9045, "sentiment": "Negative"},
        "metadata": {
          "article1": {"author": "", "title": "Another shooting in Baltimore", "timestamp": "26-FEB-1987 15:01:01.79"},
          "article2": {"author": "Anderson Silva", "title": "Street Crime up in cities", "timestamp": "06-SEP-2011 16:32:34.73"},
          "article3": {"author": "John Jones", "title": "Rise in assaults in Baltimore", "timestamp": "31-DEC-1991 01:45:59.66"}
        } 
      },
      "robbery": {
        "data": {"frequency": 15, "relevance": 0.553, "sentiment": "Positive"},
        "metadata": {
          "article1": {"author": "Rob", "title": "Robbery of Museum in Baltimore", "timestamp": "26-FEB-1987 15:01:01.79"},
          "article2": {"author": "Anderson Silva", "title": "Man held at gunpoint for wallet", "timestamp": "06-SEP-2011 16:32:34.73"},
          "article3": {"author": "John Jenkins", "title": "Increase in robbery frequency in MD", "timestamp": "31-DEC-1991 01:45:59.66"}
        } 
      }       
    }
  }
}

我正在尝试获取每个二级对象的频率计数(将巴尔的摩视为第一级)。所以在这种情况下输出应该是Baltimore.health = 3和Baltimore.crime = 27.第三级对象的数量不固定。例如,在健康状况中,可以有更多其他对象,例如“安全”或其他东西,每个对象都有自己的频率。 我想这样做:

function value(obj){
  var i=0;
  for (var x in obj){
    if(obj.hasOwnProperty(x)){
      i = i+x.frequency;
    }
  } 
  return i;
}

但是当我将一个对象传递给'Obj'时,x不会迭代对象。

1 个答案:

答案 0 :(得分:0)

正如nnnnnn所指出的那样,x是属性的名称,因此您需要使用括号语法来访问该属性。该属性中的对象没有frequency属性,该属性位于其data属性中的对象内:

function value(obj) {
  var i=0;
  for (var x in obj) {
    if (obj.hasOwnProperty(x)) {
      i += obj[x].data.frequency;
    }
  } 
  return i;
}