UNPKG

feed-jsonify

Version:

Parses RSS/Atom/XML feed data and converts it into JSON format.

35 lines (34 loc) 1.37 kB
const extractData = (value) => { var _a; return ((_a = value.match(/^<!\[CDATA\[(.*)\]\]>$/s)) === null || _a === void 0 ? void 0 : _a[1]) || value; }; const xmlJsonify = (element) => { var _a; const { children } = element; let value; if (((_a = element === null || element === void 0 ? void 0 : element.getAttribute) === null || _a === void 0 ? void 0 : _a.call(element, 'type')) === 'html') { value = extractData(element.innerHTML); } else if (children.length) { const json = {}; for (const child of children) { const tagName = child.tagName.toLowerCase(); if (!json[tagName]) json[tagName] = []; json[tagName].push(xmlJsonify(child)); } for (const tagName of Object.keys(json)) { if (json[tagName].length === 1) json[tagName] = json[tagName][0]; } value = json; } else { value = extractData(element.innerHTML); if (!value && element.tagName === 'link' && element.getAttribute('href')) value = element.getAttribute('href'); } return value; }; const feedJsonify = (feedData) => { const feedParser = new DOMParser(); return xmlJsonify(feedParser.parseFromString(feedData, 'text/xml')); }; export { feedJsonify, xmlJsonify };