Skip to content

Instantly share code, notes, and snippets.

@azu
Created November 14, 2009 13:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azu/234552 to your computer and use it in GitHub Desktop.
Save azu/234552 to your computer and use it in GitHub Desktop.
// ==UserScript==
// @name Firebug JSON formatting
// @namespace http://efcl.info/
// @include main
// ==/UserScript==
/*
参考
Firebug Chrome Authority
http://d.hatena.ne.jp/Griever/
*/
(function(){
/**
* @version 0.1.1
*/
var JSONDecoder = {};
/**
* typeofの拡張
* ArrayとかRegExpとかnullとかも判別する
*/
JSONDecoder.typeOf = function(value) {
var type = typeof value;
switch (type) {
case "object":
if (value instanceof Array) {
type = "array";
} else if (!(value instanceof Object)) {
type = "null";
}
//no break
case "function":
if (value instanceof RegExp) {
type = "regexp";
}
break;
}
return type;
}
/**
* JSONをFirebugのコンソールに書き出す
*/
JSONDecoder.toConsole = function(json) {
Application.console.log(json);
JSONDecoder.out = function(line) { Application.console.log(line); };
JSONDecoder.decode("", json, "");
}
JSONDecoder.toString = function(json) {
var decoded = "";
JSONDecoder.out = function(line) { decoded += (line + "\n"); };
JSONDecoder.decode("", json, "");
return decoded;
}
/**
* JSONを解析する
*/
JSONDecoder.decode = function(index, value, indent) {
var type = JSONDecoder.typeOf(value);
var pack = undefined;
switch (type) { //型別に見やすくする
case "object" :
pack = ["{", "}"];
break;
case "array" :
pack = ["[", "]"];
break;
case "function" :
type = "";
//no break
case "string" :
value = value.toString().replace(/\n/g, "\n" + indent); //全体をインデント
break;
case "undefined" :
type = "";
value = "undefined";
break;
case "null" :
type = "";
value = "null";
break;
}
if (type) {
type = " (" + type + ")"; //整形
}
if (pack) { //子要素がある場合は再帰処理
JSONDecoder.out(indent + index + type + pack[0]);
for (var i in value) {
JSONDecoder.decode(i, value[i], indent + "\t");
}
JSONDecoder.out(indent + pack[1]);
} else {
JSONDecoder.out(indent + index + type + ": " + value);
}
}
/**
* 文字列をObjectに変換する
*/
JSONDecoder.str2json = function(str) {
try {
eval("var json = " + str + ";");
return json;
} catch (e) {
return false;
}
}
var commandLine = document.getElementById('fbLargeCommandLine');
var toolbar = document.getElementById('fbCommandToolbar');
var Chrome = document.createElement('toolbarbutton');
Chrome.setAttribute('label', 'JSON');
toolbar.insertBefore(Chrome, toolbar.lastChild);
Chrome.addEventListener('command', function(){
JSONDecoder.toConsole(JSONDecoder.str2json(commandLine.value));
},false)
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment