JavaScriptのオブジェクトを構造解析

  function _inspect(obj) {
    if (obj === null) {
      return "null";
    } else if (obj === undefined) {
      return "undefined";
    }
    // switch use '===' to compare.
    switch(typeof obj) {
    case "number":
      return obj;
    case "string":
      return "\"" + obj.replace("\n", "\\n").repace("\r", "\\r") + "\"";
    case "function":
      return obj;
    case "java.util.ArrayList":
    case "java.util.Vector":
      var part1 = "[";
      var list = [];
      for(var index=0; index < obj.length; index++) {
        var item = obj[index];
        list.push(_inspect(item));
      }
      return (part1 + list.join(",") + "]");
    case "object":
    case "com.sun.faces.context.SessionMap":
      // Object or Array
      if (obj instanceof Array) {
        var part1 = "[";
        var list = [];
        for(var index=0; index < obj.length; index++) {
          var value = obj[index];
          list.push(_inspect(value));
        }
        if (list.length == 0) {
          // Date type has no key, convert to string.
          list.push(obj);
        }
        return (part1 + list.join(",") + "]");
      } else {
        if (typeof(obj) == "object") {
          var part1 = "{";
        } else {
          var part1 = "<" + typeof(obj) + ">:{";
        }
        var list = [];
        for(var key in obj) {
          var value = obj[key];
          if (typeof(value) != "function") {
            list.push(key + ":" + _inspect(value));
          }
        }
        if (list.length == 0) {
          // Date type has no key, convert to string.
          list.push(obj);
        }
        return (part1 + list.join(",") + "}");
      }
      break;
    default:
      return "<<" + typeof(obj) + ">>:{" + obj + "}";
    }





JavaScriptのオブジェクトを渡すと解析して文字列にしてくれる。printすればログに表示可能。
改行コードも表示できるように修正

JavaScript (Server)
yac4423
December 1, 2015 at 10:44 PM
Rating
0





No comments yetLogin first to comment...