【问题标题】:Skip HTML tags in JSON Response of walmart open APIs在沃尔玛开放 API 的 JSON 响应中跳过 HTML 标签
【发布时间】:2019-02-20 10:41:55
【问题描述】:

我们如何在没有转义 HTML 标签的情况下从沃尔玛开放 API 中获得响应

示例: 使用搜索 API 时,示例响应为

{
    "query": "ipod",
    "sort": "relevance",
    "responseGroup": "base",
    "totalResults": 257,
    "start": 1,
    "numItems": 10,
    "items": [{
        "itemId": 42608125,
        "parentItemId": 42608125,
        "name": "Apple iPod touch 32GB",
        "msrp": 247.0,
        "upc": "888462353151",
        "categoryPath": "Electronics/Portable Audio/Apple iPods/iPod Touch",
        "shortDescription": "The Apple iPod Touch 32GB is loaded with features. It is the ideal solution for carrying your music collection in your pocket. The device comes in five stunning colors, giving you plenty of options to choose from. Listen to your favorite songs from Apple Music and iTunes. It also offers the ultimate mobile gaming experience for versatility,
        "longDescription": **"<b><br>Apple iPod touch 32GB:</b><br><ul><li>Memory: 32 GB</li><li>Portable iPod touch has touchscreen controls</li><li>Bluetooth capable</li><li>Wireless LAN</li><li>Battery is built-in</li><li>4" retina display</li><li>1080p HD video recording</li><li>Up to 40 hours audio playback</li><li>8-hour video</li><li>8 Megapixel camera</li><li>Includes ear buds and charging cable</li><li>Available in Blue, Gold, Pink, White and Silver and Space Gray</li></ul>**",
}

在上面提到的 JSON 响应中,我想在获取响应时跳过 HTML 标记。

【问题讨论】:

  • 跳过是什么意思?
  • 我不想在 response@Utkanos 中使用 HTML 标记 如果您在 JSON 对象中看到上面的示例以获取 longDescription 值,则有可用的 HTML 标记。我不需要这些 html 标签
  • 您想只删除标签,还是同时删除其中的内容?
  • 只需删除标签,我需要在我的应用程序上呈现内容

标签: node.js json express walmart-api


【解决方案1】:

你可以使用下面的函数来删除 html 标签 function strip_html_tags(str) { if (!str) return; else str = str.toString(); return str.replace(/<[^>]*>/g, ''); }

【讨论】:

    【解决方案2】:

    这个简单的函数应该解码 html 实体,然后从您从该 API 获得的文本中去除 html 标记:

    function stripHtmlEntities(str) {
        let decodedHtml = decodeEntities(str);
        let el = document.createElement('span');
        el.innerHTML = decodedHtml;
        return el.textContent || el.innerText;
    }
    

    更新:要使用node.js,您没有 DOM,您应该这样做:

    const jsdom = require("jsdom");
    const { JSDOM } = jsdom;
    const dom = new JSDOM(`<!DOCTYPE html>`);
    const document = dom.window.document;
    

    当然,这个解决方案不像 Javascript 那样灵活,当然你可以找到更好的方法来剥离 HTML... :-)

    【讨论】:

    • 我正在使用nodejs,我认为没有可用的文档对象。
    • 你是对的,抱歉,没有注意到node.js 标签... :-( 更新我对目标node.js的回答...
    猜你喜欢
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2021-10-21
    • 1970-01-01
    相关资源
    最近更新 更多