解析json树结构

时间:2012-02-28 22:27:26

标签: jquery

我正在尝试输出这个json的所有元素:

{"nodes":[{"url":"asdfas","date":""},{"url":"asdfas","date":""},{"url":"asdfasfdasas","date":""}]}

这是我到目前为止的代码,但没有输出任何内容。

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  <script type="text/javascript">

var arr = "{\"nodes\":[{\"url\":\"asdfas\",\"date\":\"\"},{\"url\":\"asdfas\",\"date\":\"\"},{\"url\":\"asdfasfdasas\",\"date"\:\"\"}]}";

for(var i=0;i<arr.length;i++){
    var obj = arr[i];
    for(var key in obj){
        var attrName = key;
        var attrValue = obj[key];
        $('body').append(attrName);
    }
}

</script>

<body>
</body>

编辑:

这是我更新的文件,但仍然没有输出? :

<!DOCTYPE html>
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  <script type="text/javascript">

//Or you can parse it from a string
  var arr = JSON.parse('{\"nodes\":[{\"url\":\"asdfas\",\"date\":\"\"},{\"url\":\"asdfas\",\"date\":\"\"},{\"url\":\"asdfasfdasas\",\"date"\:\"\"}]}');

  // You have to iterate over arr.nodes, not arr
  for(var i=0;i<arr.nodes.length;i++){
      var obj = arr.nodes[i];
      for(var key in obj){
          var attrName = key;
          var attrValue = obj[key];
          $('body').append(attrName);
      }
  }

</script>
</head>

<body>




</body>
</html>

2 个答案:

答案 0 :(得分:2)

您的JSON需要被解析或不被放入字符串中;

// arr is a bad name, it is not an array, it's an object
// JSON is valid JavaScript
var arr = {"nodes":[{"url":"asdfas","date":""},{"url":"asdfas","date":""},{"url":"asdfasfdasas","date":""}]};

// Or you can parse it from a string
var arr = JSON.parse("{\"nodes\":[{\"url\":\"asdfas\",\"date\":\"\"},{\"url\":\"asdfas\",\"date\":\"\"},{\"url\":\"asdfasfdasas\",\"date\":\"\"}]}");

// You have to iterate over arr.nodes, not arr
for(var i=0;i<arr.nodes.length;i++){
    var obj = arr.nodes[i];
    for(var key in obj){
        var attrName = key;
        var attrValue = obj[key];
        $('body').append(attrName);
    }
}

答案 1 :(得分:0)

这对我有用(在chrome上测试)。我需要使用.ready函数:

<!DOCTYPE html>
<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
  <script>
  $(document).ready(function () { 
//Or you can parse it from a string
  var arr = JSON.parse('{\"nodes\":[{\"url\":\"asdfas\",\"date\":\"\"},{\"url\":\"asdfas\",\"date\":\"\"},{\"url\":\"asdfasfdasas\",\"date\":\"\"}]}');

  // You have to iterate over arr.nodes, not arr
  for(var i=0;i<arr.nodes.length;i++){
      var obj = arr.nodes[i];
      for(var key in obj){
          var attrName = key;
          var attrValue = obj[key];
          $('body').append(attrName);
      }
  }

  });

</script>
</head>

<body>




</body>
</html>