首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >解析<highlighting>标记的json数据以突出显示字段中的文本

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

Stack Overflow用户
提问于 2011-06-23 14:25:03
回答 1查看 2.9K关注 0票数 0
代码语言:javascript
复制
{
    "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> tag...one更多的东西是UID_PK's(8252,8142)<highlighting>是动态生成的每一次。如果我以如下方式获取JSON数据,请建议我如何做

代码语言:javascript
复制
$.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){

并将其解析为

代码语言:javascript
复制
$.each(newresult.response.docs, function(i,item){

代码语言:javascript
复制
 $.each(newresult.highlighting, function(i,hitem){
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-06-23 14:56:08

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

代码语言:javascript
复制
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)时有效。如果您知道要突出显示的单词在搜索结果中只出现一次,则不必使用regex:

代码语言:javascript
复制
item.description.replace(word, '<em>' + word + '</em>');
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6450102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档