将json格式的数据转换成字符串(jquery实现)

在查询$.extend方法时看到的一个列子特别好,记录下来。可以用来解析json串到数组

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<div id="log"></div>

<script>
var object1 = {
  apple: 0,
  banana: {weight: 52, price: 100},
  cherry: 97
};
var object2 = {
  banana: {price: 200},
  durian: 100
};

/* merge object2 into object1, recursively */
$.extend(true, object1, object2);

var printObj = typeof JSON != "undefined" ? JSON.stringify : function(obj) {
  var arr = [];
  $.each(obj, function(key, val) {
    var next = key + ": ";
    next += $.isPlainObject(val) ? printObj(val) : val;
    arr.push( next );
  });
  return "{ " +  arr.join(", ") + " }";
};

$("#log").append( printObj(object1) );
</script>

</body>
</html>

  地址:http://api.jquery.com/jQuery.extend/

原文地址:https://www.cnblogs.com/zhouxiuquan/p/2515036.html