Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Removing all _cdata _attributes text #199

Open
onigetoc opened this issue Feb 18, 2023 · 0 comments
Open

Removing all _cdata _attributes text #199

onigetoc opened this issue Feb 18, 2023 · 0 comments

Comments

@onigetoc
Copy link

I'm trying to convert a RSS, MRSS to Json and i do not understand why there is no options to remove all these attributes.
_attributes, _cdata , or text.

I tryed this but without success: #53

In my example, i did try but without success.

const axios = require("axios");
const { xml2js } = require("xml-js");
const striptags = require("striptags");

let limit;

async function mrssToJson(url, MRSSoptions) {
  try {
    const response = await axios.get(url);
    const xml = response.data;

const removeJsonTextAttribute = function(value, parentElement) {
  try {
    const parentOfParent = parentElement._parent;
    const pOpKeys = Object.keys(parentElement._parent);
    const keyNo = pOpKeys.length;
    const keyName = pOpKeys[keyNo - 1];
    const arrOfKey = parentElement._parent[keyName];
    const arrOfKeyLen = arrOfKey.length;
    if (arrOfKeyLen > 0) {
      const arr = arrOfKey;
      const arrIndex = arrOfKey.length - 1;
      arr[arrIndex] = value;
    } else {
      parentElement._parent[keyName] = value;
    }
  } catch (e) {}
};

function nativeType(value) {
    var nValue = Number(value);
    if (!isNaN(nValue)) {
      return nValue;
    }
    var bValue = value.toLowerCase();
    if (bValue === 'true') {
      return true;
    } else if (bValue === 'false') {
      return false;
    }
    return value;
  }
  
let options = {
  compact: true,
  nativeType: true,
  textFn: removeJsonTextAttribute,
  ignoreDeclaration: true
};

    const json = xml2js(xml, options);
    console.log(json);
    
    
    const stripHTML = str => {
      str = str.replace(/([^\n])<\/?(h|br|p|ul|ol|li|blockquote|section|table|tr|div)(?:.|\n)*?>([^\n])/gm, "$1\n$3");
      str = str.replace(/<(?:.|\n)*?>/gm, "");
      return str;
    };
    

    let sanitizedData = { channel: {}, items: [] };

    if (json.rss && json.rss.channel && json.rss.channel.item) {
      let channel = json.rss.channel;
      delete channel["content:encoded"];
      delete channel["itunes:summary"];

      Object.keys(channel).forEach(key => {
        if (key.includes(":")) {
          let newKey = key.split(":")[1];
          channel[newKey] = channel[key];
          delete channel[key];
        }
      });

      // if (channel.image) {
      //   channel.image = channel.image.$;
      // }

      //let items = json.rss.channel.item;
      let items = json.rss.channel.item;

      items = items.map(item => {
        delete item["content:encoded"];
        delete item["itunes:summary"];
        Object.keys(item).forEach(key => {
          if (key.includes(":")) {
            let newKey = key.split(":")[1];
            if (newKey === "encoded") {
              newKey = "description";
            }
            item[newKey] = item[key];
            delete item[key];
          }
        });

        return item;
      });

        //console.log('MRSSoptions: '+MRSSoptions.limit);
        
        if(MRSSoptions === undefined ){
        // if(limit === undefined || !MRSSoptions || !MRSSoptions.limit ){
            limit = 10;
        } else {
            limit = MRSSoptions.limit;
        }
        console.log(limit);
        
        items = items.slice(0, limit);

        delete json.rss.channel.item;       
            console.log(json.rss.channel);

        // json.rss.channel[0] = items['item'];
        json.rss.channel = items;
      

      items = items.map(item =>
        Object.fromEntries(
          Object.entries(item).map(([k, v]) => [k.replace("$", ""), v])
        )
      );

      sanitizedData = {
        channel: Object.fromEntries(
          Object.entries(channel).map(([k, v]) => [k.replace("$", ""), v])
        ),
        items: items.map(item =>
          Object.fromEntries(
            Object.entries(item).map(([k, v]) => [k.replace("$", ""), v])
          )
        ),
      };
      
    }

    return sanitizedData;
  } catch (error) {
    console.error(error);
  }
}

// EXAMPLE USAGE
mrssToJson("https://feeds.feedburner.com/TedtalksHD", { limit: 2 })
  .then(mrss => {
    let jsonResult = JSON.stringify(mrss, null, 2);
    console.log(mrss.items[0].title);
    console.log(mrss.items[0].description);
    console.log(mrss.items[0].enclosure);
    console.log(jsonResult);
  })
  .catch(error => {
    console.error(error);
  });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant