开发者

Parse json data for <highlighting> tag to highlight a text in a field

{
    "responseHeader": {
        "status": 0,
        "QTime": 32
    },
    "response": {
        "numFound": 21,
        "start": 0,
        "docs": [
            {
                "description": "The matte finish waves on this wedding band contrast with the high polish borders. This sharp and elegant design was finely crafted in Japan.",
                "UID_PK": "8252",

            },
            {
                "description": "This elegant ring has an Akoya cultured pearl with a band of bezel-set round diamonds making it perfect for her to wear to work or the night out.",
                "UID_PK": "8142",

            },

        ]
    },
    "highlighting": {
        "8252": {
            "description": [
                " and <em>elegant</em> design was finely crafted in Japan."
            ]
        },
        "8142": {
            "description": [
                "This <em>elegant</em> ring has an Akoya cultured pearl with a band of bezel-set round diamonds making"
            ]
        },

    }
}

This is JSON data I got from solr when i set hl=true and hl.fl=description. Here I got docs tag and highlighting tag. I need to parse highlighting tag to highlight "elegant" in description field which is in <em> tag...one more thing is UID_PK's(8252,8142) in <highlighting> are generated dynamically each time. Please suggest how can I do this if I am getting JSON data as

$.getJSON("http://192.168.1.9:8983/solr/db/select/?wt=json&&start=0&rows=20&q="+newquery+"&sort=price asc&hl=true&hl.fl=description&hl.usePhraseHighlighter=true&json.wrf=?", function(newresult){

and parsing it as

$.each(newresult.response.docs, function(i,item){

and

 $.each(newresult.highlighting, 开发者_高级运维function(i,hitem){


Assuming the response is always text and only the to be highlighted elements are enclosed in <em> tags and there is only one of them, you could do this:

var highlight = {};

$.each(newresult.highlighting, function(i, hitem){
    var match = hitem.description[0].match(/<em>(.*?)<\/em>/);
    highlight[i] = match[1];
});

$.each(newresult.response.docs, function(i, item){
    var word = highlight[item["UID_PK"]];
    var result = item.description.replace(new RegExp(word, 'g'), '<em>' + word + '</em>');
    // do something with the result
});

This only works if word does not contain nay special regular expression characters (in which case you'd have to escape them). If you know that the to be highlighted word only occurs once in the search results, you don't have to use regex:

item.description.replace(word, '<em>' + word + '</em>');

DEMO

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜