html2json.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. !function(e){
  2. if("object" == typeof exports && "undefined" != typeof module){
  3. module.exports = e();
  4. }else if ("function" == typeof define && define.amd){
  5. define([], e);
  6. }else{
  7. var r;
  8. r = "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : this, r.html2json = e()
  9. };
  10. }(function(){
  11. // Regular Expressions for parsing tags and attributes
  12. var startTag = /^<([-A-Za-z0-9_]+)((?:\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,
  13. endTag = /^<\/([-A-Za-z0-9_]+)[^>]*>/,
  14. attr = /([a-zA-Z_:][-a-zA-Z0-9_:.]*)(?:\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))?/g;
  15. // Empty Elements - HTML 5
  16. var empty = makeMap("area,base,basefont,br,col,frame,hr,img,input,link,meta,param,embed,command,keygen,source,track,wbr");
  17. // Block Elements - HTML 5
  18. var block = makeMap("a,address,article,applet,aside,audio,blockquote,button,canvas,center,dd,del,dir,div,dl,dt,fieldset,figcaption,figure,footer,form,frameset,h1,h2,h3,h4,h5,h6,header,hgroup,hr,iframe,ins,isindex,li,map,menu,noframes,noscript,object,ol,output,p,pre,section,script,table,tbody,td,tfoot,th,thead,tr,ul,video");
  19. // Inline Elements - HTML 5
  20. var inline = makeMap("abbr,acronym,applet,b,basefont,bdo,big,br,button,cite,code,del,dfn,em,font,i,iframe,img,input,ins,kbd,label,map,object,q,s,samp,script,select,small,span,strike,strong,sub,sup,textarea,tt,u,var");
  21. // Elements that you can, intentionally, leave open
  22. // (and which close themselves)
  23. var closeSelf = makeMap("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr");
  24. // Attributes that have their values filled in disabled="disabled"
  25. var fillAttrs = makeMap("checked,compact,declare,defer,disabled,ismap,multiple,nohref,noresize,noshade,nowrap,readonly,selected");
  26. // Special Elements (can contain anything)
  27. var special = makeMap("script,style");
  28. var HTMLParser = function (html, handler) {
  29. var index, chars, match, stack = [], last = html;
  30. stack.last = function () {
  31. return this[this.length - 1];
  32. };
  33. while (html) {
  34. chars = true;
  35. // Make sure we're not in a script or style element
  36. if (!stack.last() || !special[stack.last()]) {
  37. // Comment
  38. if (html.indexOf("<!--") == 0) {
  39. index = html.indexOf("-->");
  40. if (index >= 0) {
  41. if (handler.comment)
  42. handler.comment(html.substring(4, index));
  43. html = html.substring(index + 3);
  44. chars = false;
  45. }
  46. // end tag
  47. } else if (html.indexOf("</") == 0) {
  48. match = html.match(endTag);
  49. if (match) {
  50. html = html.substring(match[0].length);
  51. match[0].replace(endTag, parseEndTag);
  52. chars = false;
  53. }
  54. // start tag
  55. } else if (html.indexOf("<") == 0) {
  56. match = html.match(startTag);
  57. if (match) {
  58. html = html.substring(match[0].length);
  59. match[0].replace(startTag, parseStartTag);
  60. chars = false;
  61. }
  62. }
  63. if (chars) {
  64. index = html.indexOf("<");
  65. var text = index < 0 ? html : html.substring(0, index);
  66. html = index < 0 ? "" : html.substring(index);
  67. if (handler.chars)
  68. handler.chars(text);
  69. }
  70. } else {
  71. html = html.replace(new RegExp("([\\s\\S]*?)<\/" + stack.last() + "[^>]*>"), function (all, text) {
  72. text = text.replace(/<!--([\s\S]*?)-->|<!\[CDATA\[([\s\S]*?)]]>/g, "$1$2");
  73. if (handler.chars)
  74. handler.chars(text);
  75. return "";
  76. });
  77. parseEndTag("", stack.last());
  78. }
  79. if (html == last)
  80. throw "Parse Error: " + html;
  81. last = html;
  82. }
  83. // Clean up any remaining tags
  84. parseEndTag();
  85. function parseStartTag(tag, tagName, rest, unary) {
  86. tagName = tagName.toLowerCase();
  87. if (block[tagName]) {
  88. while (stack.last() && inline[stack.last()]) {
  89. parseEndTag("", stack.last());
  90. }
  91. }
  92. if (closeSelf[tagName] && stack.last() == tagName) {
  93. parseEndTag("", tagName);
  94. }
  95. unary = empty[tagName] || !!unary;
  96. if (!unary)
  97. stack.push(tagName);
  98. if (handler.start) {
  99. var attrs = [];
  100. rest.replace(attr, function (match, name) {
  101. var value = arguments[2] ? arguments[2] :
  102. arguments[3] ? arguments[3] :
  103. arguments[4] ? arguments[4] :
  104. fillAttrs[name] ? name : "";
  105. attrs.push({
  106. name: name,
  107. value: value,
  108. escaped: value.replace(/(^|[^\\])"/g, '$1\\\"') //"
  109. });
  110. });
  111. if (handler.start)
  112. handler.start(tagName, attrs, unary);
  113. }
  114. }
  115. function parseEndTag(tag, tagName) {
  116. // If no tag name is provided, clean shop
  117. if (!tagName)
  118. var pos = 0;
  119. // Find the closest opened tag of the same type
  120. else
  121. for (var pos = stack.length - 1; pos >= 0; pos--)
  122. if (stack[pos] == tagName)
  123. break;
  124. if (pos >= 0) {
  125. // Close all the open elements, up the stack
  126. for (var i = stack.length - 1; i >= pos; i--)
  127. if (handler.end)
  128. handler.end(stack[i]);
  129. // Remove the open elements from the stack
  130. stack.length = pos;
  131. }
  132. }
  133. };
  134. var HTMLtoXML = function (html) {
  135. var results = "";
  136. HTMLParser(html, {
  137. start: function (tag, attrs, unary) {
  138. results += "<" + tag;
  139. for (var i = 0; i < attrs.length; i++)
  140. results += " " + attrs[i].name + '="' + attrs[i].escaped + '"';
  141. results += ">";
  142. },
  143. end: function (tag) {
  144. results += "</" + tag + ">";
  145. },
  146. chars: function (text) {
  147. results += text;
  148. },
  149. comment: function (text) {
  150. results += "<!--" + text + "-->";
  151. }
  152. });
  153. return results;
  154. };
  155. var HTMLtoDOM = function (html, doc) {
  156. // There can be only one of these elements
  157. var one = makeMap("html,head,body,title");
  158. // Enforce a structure for the document
  159. var structure = {
  160. link: "head",
  161. base: "head"
  162. };
  163. if (!doc) {
  164. if (typeof DOMDocument != "undefined")
  165. doc = new DOMDocument();
  166. else if (typeof document != "undefined" && document.implementation && document.implementation.createDocument)
  167. doc = document.implementation.createDocument("", "", null);
  168. else if (typeof ActiveX != "undefined")
  169. doc = new ActiveXObject("Msxml.DOMDocument");
  170. } else
  171. doc = doc.ownerDocument ||
  172. doc.getOwnerDocument && doc.getOwnerDocument() ||
  173. doc;
  174. var elems = [],
  175. documentElement = doc.documentElement ||
  176. doc.getDocumentElement && doc.getDocumentElement();
  177. // If we're dealing with an empty document then we
  178. // need to pre-populate it with the HTML document structure
  179. if (!documentElement && doc.createElement) (function () {
  180. var html = doc.createElement("html");
  181. var head = doc.createElement("head");
  182. head.appendChild(doc.createElement("title"));
  183. html.appendChild(head);
  184. html.appendChild(doc.createElement("body"));
  185. doc.appendChild(html);
  186. })();
  187. // Find all the unique elements
  188. if (doc.getElementsByTagName)
  189. for (var i in one)
  190. one[i] = doc.getElementsByTagName(i)[0];
  191. // If we're working with a document, inject contents into
  192. // the body element
  193. var curParentNode = one.body;
  194. HTMLParser(html, {
  195. start: function (tagName, attrs, unary) {
  196. // If it's a pre-built element, then we can ignore
  197. // its construction
  198. if (one[tagName]) {
  199. curParentNode = one[tagName];
  200. if (!unary) {
  201. elems.push(curParentNode);
  202. }
  203. return;
  204. }
  205. var elem = doc.createElement(tagName);
  206. for (var attr in attrs)
  207. elem.setAttribute(attrs[attr].name, attrs[attr].value);
  208. if (structure[tagName] && typeof one[structure[tagName]] != "boolean")
  209. one[structure[tagName]].appendChild(elem);
  210. else if (curParentNode && curParentNode.appendChild)
  211. curParentNode.appendChild(elem);
  212. if (!unary) {
  213. elems.push(elem);
  214. curParentNode = elem;
  215. }
  216. },
  217. end: function (tag) {
  218. elems.length -= 1;
  219. // Init the new parentNode
  220. curParentNode = elems[elems.length - 1];
  221. },
  222. chars: function (text) {
  223. curParentNode.appendChild(doc.createTextNode(text));
  224. },
  225. comment: function (text) {
  226. // create comment node
  227. }
  228. });
  229. return doc;
  230. };
  231. function makeMap(str) {
  232. var obj = {}, items = str.split(",");
  233. for (var i = 0; i < items.length; i++)
  234. obj[items[i]] = true;
  235. return obj;
  236. }
  237. function q(v) {
  238. return '"' + v + '"';
  239. }
  240. function removeDOCTYPE(html) {
  241. return html
  242. .replace(/<\?xml.*\?>\n/, '')
  243. .replace(/<!doctype.*\>\n/, '')
  244. .replace(/<!DOCTYPE.*\>\n/, '');
  245. }
  246. let html2json = function html2json(html) {
  247. html = removeDOCTYPE(html);
  248. var bufArray = [];
  249. var results = {
  250. node: 'root',
  251. child: [],
  252. };
  253. HTMLParser(html, {
  254. start: function(tag, attrs, unary) {
  255. // node for this element
  256. var node = {
  257. node: 'element',
  258. tag: tag,
  259. };
  260. if (attrs.length !== 0) {
  261. node.attr = attrs.reduce(function(pre, attr) {
  262. var name = attr.name;
  263. var value = attr.value;
  264. // has multi attibutes
  265. // make it array of attribute
  266. if (value.match(/ /)) {
  267. value = value.split(' ');
  268. }
  269. // if attr already exists
  270. // merge it
  271. if (pre[name]) {
  272. if (Array.isArray(pre[name])) {
  273. // already array, push to last
  274. pre[name].push(value);
  275. } else {
  276. // single value, make it array
  277. pre[name] = [pre[name], value];
  278. }
  279. } else {
  280. // not exist, put it
  281. pre[name] = value;
  282. }
  283. return pre;
  284. }, {});
  285. }
  286. if (unary) {
  287. // if this tag dosen't have end tag
  288. // like <img src="hoge.png"/>
  289. // add to parents
  290. var parent = bufArray[0] || results;
  291. if (parent.child === undefined) {
  292. parent.child = [];
  293. }
  294. parent.child.push(node);
  295. } else {
  296. bufArray.unshift(node);
  297. }
  298. },
  299. end: function(tag) {
  300. // merge into parent tag
  301. var node = bufArray.shift();
  302. if (node.tag !== tag) console.error('invalid state: mismatch end tag');
  303. if (bufArray.length === 0) {
  304. results.child.push(node);
  305. } else {
  306. var parent = bufArray[0];
  307. if (parent.child === undefined) {
  308. parent.child = [];
  309. }
  310. parent.child.push(node);
  311. }
  312. },
  313. chars: function(text) {
  314. var node = {
  315. node: 'text',
  316. text: text,
  317. };
  318. if (bufArray.length === 0) {
  319. results.child.push(node);
  320. } else {
  321. var parent = bufArray[0];
  322. if (parent.child === undefined) {
  323. parent.child = [];
  324. }
  325. parent.child.push(node);
  326. }
  327. },
  328. comment: function(text) {
  329. var node = {
  330. node: 'comment',
  331. text: text,
  332. };
  333. var parent = bufArray[0];
  334. if (parent.child === undefined) {
  335. parent.child = [];
  336. }
  337. parent.child.push(node);
  338. },
  339. });
  340. return results;
  341. };
  342. return html2json;
  343. });