解析<highlighting>标签的json数据以突出显示字段中的文本</highlighting>

时间:2011-06-23 06:25:03

标签: javascript jquery json solr

{
    "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"
            ]
        },

    }
}

这是我在设置hl=truehl.fl=description时从solr获得的JSON数据。在这里,我获得了docs代码和highlighting代码。我需要解析highlighting标记,在<em>标记中的说明字段中突出显示“优雅”...每次动态生成UID_PK's(8252,8142)中的<highlighting>还有一件事。如果我将JSON数据作为

,请建议我该怎么做
$.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){

并将其解析为

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

 $.each(newresult.highlighting, function(i,hitem){

1 个答案:

答案 0 :(得分:1)

假设响应始终是文本,并且只有要突出显示的元素包含在<em>标记中,并且只有其中一个,您可以这样做:

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
});

仅当word不包含任何特殊正则表达式字符(in which case you'd have to escape them)时才有效。如果您知道要突出显示的单词仅在搜索结果中出现一次,则不必使用正则表达式:

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

DEMO