json-viewer.js案例

【前言】插件Github地址

【需求】页面上实时预览Json字符串,相当于Json在线格式化。

【效果】

【代码(复制可用)】

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>json-viewer.js案例</title><style>/* [jquery.json-viewer.css] START *//* Root element */.json-document {padding: 1em 2em;}/* Syntax highlighting for JSON objects */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;}/* Toggle button */a.json-toggle {position: relative;color: inherit;text-decoration: none;}a.json-toggle:focus {outline: none;}a.json-toggle:before {font-size: 1.1em;color: #c0c0c0;content: "\25BC"; /* down arrow */position: absolute;display: inline-block;width: 1em;text-align: center;line-height: 1em;left: -1.2em;}a.json-toggle:hover:before {color: #aaa;}a.json-toggle.collapsed:before {/* Use rotated down arrow, prevents right arrow appearing smaller than down arrow in some browsers */transform: rotate(-90deg);}/* Collapsable placeholder links */a.json-placeholder {color: #aaa;padding: 0 1em;text-decoration: none;}a.json-placeholder:hover {text-decoration: underline;}/* [jquery.json-viewer.css] END */body {margin: 0 100px;font-family: sans-serif;}p.options label {margin-right: 10px;}p.options input[type=checkbox] {vertical-align: middle;}textarea#json-input {width: 100%;height: 200px;}pre#json-renderer {border: 1px solid #aaa;}</style><script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
</head>
<body><h1><a href="https://github.com/abodelot/jquery.json-viewer">jQuery json-viewer</a></h1><textarea id="json-input" autocomplete="off">{"id": 1001,"type": "donut","name": "Cake","description": "https://en.wikipedia.org/wiki/Doughnut","price": 2.55,"available": {store: 42,warehouse: 600},"toppings": [{ "id": 5001, "type": "None" },{ "id": 5002, "type": "Glazed" },{ "id": 5005, "type": "Sugar" },{ "id": 5003, "type": "Chocolate" },{ "id": 5004, "type": "Maple" }],"uuids": ["826b23ce-2669-4122-981f-3e2e4429159d","e32111a0-6a87-49ab-b58f-a01bf8d28ba0","c055a894-698e-41c0-b85f-7510a7351d9d",],}</textarea><p class="options">Options:<label title="Generate node as collapsed"><input type="checkbox" id="collapsed">Collapse nodes</label><label title="Allow root element to be collasped"><input type="checkbox" id="root-collapsable" checked>Root collapsable</label><label title="Surround keys with quotes"><input type="checkbox" id="with-quotes">Keys with quotes</label><label title="Generate anchor tags for URL values"><input type="checkbox" id="with-links" checked>With Links</label></p><button id="btn-json-viewer" title="run jsonViewer()">Transform to HTML</button><pre id="json-renderer"></pre>
</body>
<script>$(function() {function renderJson() {try {var input = eval('(' + $('#json-input').val() + ')');}catch (error) {return alert("Cannot eval JSON: " + error);}var options = {collapsed: $('#collapsed').is(':checked'),rootCollapsable: $('#root-collapsable').is(':checked'),withQuotes: $('#with-quotes').is(':checked'),withLinks: $('#with-links').is(':checked')};$('#json-renderer').jsonViewer(input, options);}// Generate on click$('#btn-json-viewer').click(renderJson);// Generate on option change$('p.options input[type=checkbox]').click(renderJson);// Display JSON sample on page loadrenderJson();});//[jquery.json-viewer.js] START/*** jQuery json-viewer* @author: Alexandre Bodelot <alexandre.bodelot@gmail.com>* @link: https://github.com/abodelot/jquery.json-viewer*/(function($) {/*** Check if arg is either an array with at least 1 element, or a dict with at least 1 key* @return boolean*/function isCollapsable(arg) {return arg instanceof Object && Object.keys(arg).length > 0;}/*** Check if a string represents a valid url* @return boolean*/function isUrl(string) {var urlRegexp = /^(https?:\/\/|ftps?:\/\/)?([a-z0-9%-]+\.){1,}([a-z0-9-]+)?(:(\d{1,5}))?(\/([a-z0-9\-._~:/?#[\]@!$&'()*+,;=%]+)?)?$/i;return urlRegexp.test(string);}/*** Transform a json object into html representation* @return string*/function json2html(json, options) {var html = '';if (typeof json === 'string') {// Escape tags and quotesjson = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&apos;').replace(/"/g, '&quot;');if (options.withLinks && isUrl(json)) {html += '<a href="' + json + '" class="json-string" target="_blank">' + json + '</a>';} else {// Escape double quotes in the rendered non-URL string.json = json.replace(/&quot;/g, '\\&quot;');html += '<span class="json-string">"' + json + '"</span>';}} else if (typeof json === 'number') {html += '<span class="json-literal">' + json + '</span>';} else if (typeof json === 'boolean') {html += '<span class="json-literal">' + json + '</span>';} else if (json === null) {html += '<span class="json-literal">null</span>';} else if (json instanceof Array) {if (json.length > 0) {html += '[<ol class="json-array">';for (var i = 0; i < json.length; ++i) {html += '<li>';// Add toggle button if item is collapsableif (isCollapsable(json[i])) {html += '<a href class="json-toggle"></a>';}html += json2html(json[i], options);// Add comma if item is not lastif (i < json.length - 1) {html += ',';}html += '</li>';}html += '</ol>]';} else {html += '[]';}} else if (typeof json === 'object') {var keyCount = Object.keys(json).length;if (keyCount > 0) {html += '{<ul class="json-dict">';for (var key in json) {if (Object.prototype.hasOwnProperty.call(json, key)) {html += '<li>';var keyRepr = options.withQuotes ?'<span class="json-string">"' + key + '"</span>' : key;// Add toggle button if item is collapsableif (isCollapsable(json[key])) {html += '<a href class="json-toggle">' + keyRepr + '</a>';} else {html += keyRepr;}html += ': ' + json2html(json[key], options);// Add comma if item is not lastif (--keyCount > 0) {html += ',';}html += '</li>';}}html += '</ul>}';} else {html += '{}';}}return html;}/*** jQuery plugin method* @param json: a javascript object* @param options: an optional options hash*/$.fn.jsonViewer = function(json, options) {// Merge user options with default optionsoptions = Object.assign({}, {collapsed: false,rootCollapsable: true,withQuotes: false,withLinks: true}, options);// jQuery chainingreturn this.each(function() {// Transform to HTMLvar html = json2html(json, options);if (options.rootCollapsable && isCollapsable(json)) {html = '<a href class="json-toggle"></a>' + html;}// Insert HTML in target DOM element$(this).html(html);$(this).addClass('json-document');// Bind click on toggle buttons$(this).off('click');$(this).on('click', 'a.json-toggle', function() {var target = $(this).toggleClass('collapsed').siblings('ul.json-dict, ol.json-array');target.toggle();if (target.is(':visible')) {target.siblings('.json-placeholder').remove();} else {var count = target.children('li').length;var placeholder = count + (count > 1 ? ' items' : ' item');target.after('<a href class="json-placeholder">' + placeholder + '</a>');}return false;});// Simulate click on toggle button when placeholder is clicked$(this).on('click', 'a.json-placeholder', function() {$(this).siblings('a.json-toggle').click();return false;});if (options.collapsed == true) {// Trigger click to collapse all nodes$(this).find('a.json-toggle').click();}});};})(jQuery);//[jquery.json-viewer.js] END
</script>
</html>

json-viewer.js案例相关推荐

  1. JS案例:使用对象、对象数组、正则表达式

    JS案例:使用对象.对象数组.正则表达式 1.使用对象 声明对象变量,其实就是将一个json对象赋给一个变量,可以看到json对象就由一些键值对构成. 运行效果: 如果将{id: 3, name: & ...

  2. 使用JsonEditor开源组件写了一个Json Viewer

    工作中经常要查看一些无格式化的json数据, 下载了几个桌面的json应用, 都不是很理想. 以前常用的都是一些在线的json viewer. 比如[url=http://json.parser.on ...

  3. 内置对象的API Array数组对象 String字符串对象 json字符串 JSON对象 js作用域及变量预解析 引用类型与值类型区别 共享引用 基本包装类型 数组去重

    01-内置对象的API a.Date对象获取时间 b.Array对象数组加工 c.String对象字符串加工 d.json字符串的语法格式 e.JSON对象的字符串与对象转换应用 02-JS作用域 a ...

  4. json数组 js html标签,js定义json对象数组 json 数组也是数组 //

    var jsonstr="[{'name':'a','value':1},{'name':'b','value':2}]"; var jsonarray = eval('('+js ...

  5. viewer.js插件的应用

    需求:商品列表中图片点击放大. 实现方法:使用viewer.js插件,实现点击图片图片放大 做法: 1.下载viewer.js插件 2.页面上引入相关的插件 <link rel="st ...

  6. php将字符串转换为json格式,js中将字符串转换为json格式的三种方法

    json在js的开发过程中经常会用到,像在使用ajax开发的项目过程中,经常需要将json格式的字符串返回到前端,前端解析成json对象. 下面为大家介绍下将字符串转换为json对象的三种常用的方法: ...

  7. JSON与JS对象的区别

    和一些同学一样:总是感觉json对象(其实json不是对象)和js对象的字面量表示法相同,最近学习json,真心搞不懂,js对象和json有什么区别?就是感觉json的key要用" &quo ...

  8. viewer.js实现预览效果

    我是歌谣 放弃很容易 但是坚持一定很酷 微信公众号关注小歌谣 日常分享前后端知识 前言 最近涉及一个移动端项目 需要把其中的图片变成可预览的图片 听学弟说 可以利用viewer进行实现 首先 我们需要 ...

  9. 强大的jQuery图片查看器插件Viewer.js

    简介 Viewer.js 是一款强大的图片查看器 Viewer.js 有以下特点: 支持移动设备触摸事件 支持响应式 支持放大/缩小 支持旋转(类似微博的图片旋转) 支持水平/垂直翻转 支持图片移动 ...

  10. Viewer.js 图片预览插件

    一.简介 Viewer.js 是一款强大的图片查看器. Viewer.js 有以下特点: 支持移动设备触摸事件 支持响应式 支持放大/缩小 支持旋转(类似微博的图片旋转) 支持水平/垂直翻转 支持图片 ...

最新文章

  1. Python的零基础超详细讲解(第三天)-Python的基础语法
  2. mongochef如何链接有权限的mongodb3.x数据库
  3. 查看源代码不方便?我有利器
  4. mysql 烂泥_烂泥:学习mysql的binlog配置
  5. LeetCode 69. Sqrt(x)
  6. SVN服务器使用(一)
  7. Linux下c编程设置串口属性和读写串口操作说明总结
  8. 创龙 C6000 DSP开发板众筹来袭
  9. SceneCAD: Predicting Object Alignmentsand Layouts in RGB-D Scans
  10. 【FFmpeg学习】H264 视频编码格式详细总结
  11. Lu窗口库LuWin
  12. 产品策划五:App升级系统策划方案
  13. Qt之动态属性unpolish()和polish()
  14. Token登录验证(附图)
  15. 100天成就卓越领导力:新晋领导者的First100训练法
  16. python14 Prompting and Passing
  17. 如何使用GAF进行地图应用的定制开发
  18. 微信小程序账号长时间未登录冻结解封
  19. Detectron2安装踩坑记录(比较详细版)
  20. 鼠标点击控制div层展开收缩

热门文章

  1. 计算机软件技术基础_「连载」信息技术基础题型归纳之计算机软件2
  2. 链表常见操作java实现二:反转链表,从尾到头倒序遍历
  3. 挖金矿 详解(C++)
  4. js怎么实现数组里的数据相加_C++如何实现大整数相加
  5. local.china java_java-JDBC无法登录到LocalDB实例,但是在SSMS中,...
  6. 全科初高中智能学习机器人_智能学习机器人推荐,阿尔法蛋大蛋2.0学习内容智能推荐...
  7. 初中生学计算机应用有什么好方面,计算机有哪些专业 初中毕业学习相关专业有发展吗...
  8. Linux 进程内存掉电保存,Shell脚本可在Linux断电时停止应用程序
  9. python mro算法_Python MRO C3算法实现
  10. arduino动态刷新显示_Arduino驱动TFT彩色触摸屏-有没有更好的方法?