在Walmart开放式API的JSON响应中跳过HTML标签

时间:2019-02-20 10:41:55

标签: node.js json express walmart-api

在沃尔玛开放API的

中,如何在不转义HTML标记的情况下获得响应

示例: 使用搜索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标签。

2 个答案:

答案 0 :(得分:0)

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

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

更新:要在没有DOM的node.js上使用,应执行以下操作:

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

当然,此解决方案并不像Javascript那样精巧,可以肯定的是,您可以找到剥离HTML的更好方法... :-)

答案 1 :(得分:0)

您可以使用以下功能删除html标签 function strip_html_tags(str) { if (!str) return; else str = str.toString(); return str.replace(/&lt;[^&gt;]*&gt;/g, ''); }