json-viewer

// 解决和原网页jquery版本冲突

当前为 2020-01-17 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name json-viewer
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.3
  5. // @description // 解决和原网页jquery版本冲突
  6. // @description 增加判断,当是访问的json接口地址的时候才初始化json格式化插件到页面
  7. // @description 谷歌浏览器直接打开json格式内容的接口地址,可以格式化显示接口返回值,保留key的双引号,支持图片链接预览
  8. // @author sgd
  9. // @match *://*/*
  10. // @grant none
  11. // @require https://code.jquery.com/jquery-3.4.1.min.js
  12. // @icon https://www.easyicon.net/api/resizeApi.php?id=501159&size=128
  13. // ==/UserScript==
  14.  
  15.  
  16. // 解决和原网页jquery版本冲突
  17. var jq = jQuery.noConflict(true);
  18.  
  19. // jquery.json-viewer 插件 开始
  20. (function(jq){
  21. function isCollapsable(arg) {
  22. return arg instanceof Object && Object.keys(arg).length > 0;
  23. }
  24. function isUrl(string) {
  25. var regexp = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
  26. return regexp.test(string);
  27. }
  28. function json2html(json, options) {
  29. var html = '';
  30. if (typeof json === 'string') {
  31. /* Escape tags */
  32. json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  33. if (isUrl(json)){
  34. html += '<a href="' + json + '" class="json-string">"' + json + '"</a>';
  35. }
  36. else{
  37. html += '<span class="json-string">"' + json + '"</span>';
  38. }
  39. }
  40. else if (typeof json === 'number') {
  41. html += '<span class="json-literal">' + json + '</span>';
  42. }
  43. else if (typeof json === 'boolean') {
  44. html += '<span class="json-literal">' + json + '</span>';
  45. }
  46. else if (json === null) {
  47. html += '<span class="json-literal">null</span>';
  48. }
  49. else if (json instanceof Array) {
  50. if (json.length > 0) {
  51. html += '[<ol class="json-array">';
  52. for (var i = 0; i < json.length; ++i) {
  53. html += '<li>';
  54. /* Add toggle button if item is collapsable */
  55. if (isCollapsable(json[i])) {
  56. html += '<a href class="json-toggle"></a>';
  57. }
  58. html += json2html(json[i], options);
  59. /* Add comma if item is not last */
  60. if (i < json.length - 1) {
  61. html += ',';
  62. }
  63. html += '</li>';
  64. }
  65. html += '</ol>]';
  66. }
  67. else {
  68. html += '[]';
  69. }
  70. }
  71. else if (typeof json === 'object') {
  72. var key_count = Object.keys(json).length;
  73. if (key_count > 0) {
  74. html += '{<ul class="json-dict">';
  75. for (var key in json) {
  76. if (json.hasOwnProperty(key)) {
  77. html += '<li>';
  78. var keyRepr = options.withQuotes ?
  79. '<span class="json-string">"' + key + '"</span>' : key;
  80. /* Add toggle button if item is collapsable */
  81. if (isCollapsable(json[key])) {
  82. html += '<a href class="json-toggle">' + keyRepr + '</a>';
  83. }
  84. else {
  85. html += keyRepr;
  86. }
  87. html += ': ' + json2html(json[key], options);
  88. /* Add comma if item is not last */
  89. if (--key_count > 0){
  90. html += ',';
  91. }
  92. html += '</li>';
  93. }
  94. }
  95. html += '</ul>}';
  96. }
  97. else {
  98. html += '{}';
  99. }
  100. }
  101. return html;
  102. }
  103. jq.fn.jsonViewer = function(json, options) {
  104. options = options || {};
  105. return this.each(function() {
  106.  
  107. /* Transform to HTML */
  108. var html = json2html(json, options);
  109. if (isCollapsable(json)){
  110. html = '<a href class="json-toggle"></a>' + html;
  111. }
  112. /* Insert HTML in target DOM element */
  113. jq(this).html(html);
  114.  
  115. /* Bind click on toggle buttons */
  116. jq(this).off('click');
  117. jq(this).on('click', 'a.json-toggle', function() {
  118. var target = jq(this).toggleClass('collapsed').siblings('ul.json-dict, ol.json-array');
  119. target.toggle();
  120. if (target.is(':visible')) {
  121. target.siblings('.json-placeholder').remove();
  122. }
  123. else {
  124. var count = target.children('li').length;
  125. var placeholder = count + (count > 1 ? ' items' : ' item');
  126. target.after('<a href class="json-placeholder">' + placeholder + '</a>');
  127. }
  128. return false;
  129. });
  130.  
  131. /* Simulate click on toggle button when placeholder is clicked */
  132. jq(this).on('click', 'a.json-placeholder', function() {
  133. jq(this).siblings('a.json-toggle').click();
  134. return false;
  135. });
  136.  
  137. if (options.collapsed == true) {
  138. /* Trigger click to collapse all nodes */
  139. jq(this).find('a.json-toggle').click();
  140. }
  141. });
  142. };
  143. })(jq);
  144. // jquery.json-viewer 插件 结束
  145.  
  146. (function() {
  147. 'use strict';
  148. // 添加样式
  149. var style = document.createElement("style");
  150. style.type = "text/css";
  151. var text = document.createTextNode("body{margin-bottom: 200px;}per{margin:20px;}#btn{position: fixed;top: 20px;right: 20px;background-color: transparent;border: 1px solid rgb(218, 220, 224);border-radius: 4px;box-sizing: border-box;color: rgb(26, 115, 232);cursor: pointer;line-height:30px;}#btn:hover{background-color:rgb(210, 227, 252);} ul.json-dict, ol.json-array {list-style-type: none;margin: 0 0 0 1px;border-left: 1px dotted #ccc;padding-left: 2em;}.json-string {color: #0B7500;}.json-literal {color: #1A01CC;font-weight: bold;}a.json-toggle {position: relative;color: inherit;text-decoration: none;}a.json-toggle:focus {outline: none;}a.json-toggle:before {color: #aaa;content: \"\\25BC\";position: absolute;display: inline-block;width: 1em;left: -1em;}a.json-toggle.collapsed:before {transform: rotate(-90deg);-ms-transform: rotate(-90deg);-webkit-transform: rotate(-90deg);}a.json-placeholder {color: #aaa;padding: 0 1em;text-decoration: none;} a.json-placeholder:hover { text-decoration: underline; }");
  152. style.appendChild(text);
  153. var head = document.getElementsByTagName("head")[0];
  154. head.appendChild(style);
  155.  
  156. var source = jq('pre[style="word-wrap: break-word; white-space: pre-wrap;"]');
  157. // 根据上面这一点没办法确定是需要添加json格式化工具,再加上对内容进行判断是不是json格式的内容
  158.  
  159. // 如果是直接打开的json接口地址才需要格式化插件
  160. if(source.length > 0 && isJSON(source.html())){
  161. console.log("json-viewer 插件初始化成功");
  162. source.attr("id", "json-source")
  163. source.hide();
  164. var src = source.html();// 获取到内容
  165. // 添加一个格式化显示的per元素
  166. jq("body").append(jq('<per id="json-renderer"></pre>'))
  167. console.log(src);
  168. // 将内容用eval函数处理下
  169. var input = eval('(' + src + ')');
  170. // 调用格式化方法,参数:是否收缩所有的节点 是否为Key添加双引号
  171. jq('#json-renderer').jsonViewer(input, {collapsed: false,withQuotes: true});
  172.  
  173. // 添加原文、格式化后内容的切换按钮
  174. jq("body").append('<input type="button" value="View Source" id="btn"/>');
  175. jq("body").on("click","#btn",function(){
  176. var v = jq(this).val();
  177. if(v=='View Source'){
  178. jq(this).val("Format Content");
  179. // 查看原文
  180. jq('#json-renderer').hide();
  181. jq('#json-source').show();
  182. }else{
  183. jq(this).val("View Source");
  184. // 格式化
  185. jq('#json-renderer').show();
  186. jq('#json-source').hide();
  187. }
  188. });
  189.  
  190. // 所有a标签,看是否是图片,是图片生成预览图
  191. jq(document).on("mouseenter mouseleave","a.json-string",function(event){
  192. if(event.type=='mouseenter'){
  193. // 移入
  194. var href = jq(this).attr('href');
  195. if(isImg(href)){
  196. jq("body").append('<div style="display:none; position: absolute;width:300px;height:200px;" class="preview"><img style="width:100%;height:100%;" src="'+ href +'" /></div>');
  197. var xPos = parseInt(event.pageX) + "px";
  198. var yPos = parseInt(event.pageY) + "px";
  199. jq(".preview").css("left", xPos);
  200. jq(".preview").css("top", yPos);
  201. jq(".preview").show();
  202. }
  203. }else{
  204. // 移除
  205. jq(".preview").remove();
  206. }
  207.  
  208. });
  209. }
  210.  
  211. /*检查是否是图片链接*/
  212. function isImg(pathImg) {
  213. var regexp = /^(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?\/([\w#!:.?+=&%@!\-\/])*\.(gif|jpg|jpeg|png|GIF|JPG|PNG)([\w#!:.?+=&%@!\-\/])?/;
  214. return regexp.test(pathImg);
  215. }
  216. /** 检验内容是否是json格式的内容*/
  217. function isJSON(str) {
  218. if (typeof str == 'string') {
  219. try {
  220. var obj=JSON.parse(str);
  221. if(typeof obj == 'object' && obj ){
  222. return true;
  223. }else{
  224. return false;
  225. }
  226.  
  227. } catch(e) {
  228. console.log('error:'+str+'!!!'+e);
  229. return false;
  230. }
  231. }
  232. console.log('It is not a string!')
  233. }
  234.  
  235.  
  236. })();