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

{ "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 elegant design was finely crafted in Japan." ] }, "8142": { "description": [ "This elegant ring has an Akoya cultured pearl with a band of bezel-set round diamonds making" ] }, } } 

这是我在设置hl=truehl.fl=description时从solr获得的JSON数据。 在这里,我获得了docs标签和highlighting标签。 我需要解析highlighting标签以在标签中的描述字段中突出显示“优雅”…还有一件事是中的UID_PK's(8252,8142)每次都是动态生成的。 如果我正在获取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){ 

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

 var highlight = {}; $.each(newresult.highlighting, function(i, hitem){ var match = hitem.description[0].match(/(.*?)<\/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'), '' + word + ''); // do something with the result }); 

这仅适用于word不包含任何特殊正则表达式字符的情况( 在这种情况下,您必须转义它们 )。 如果您知道要突出显示的单词仅在搜索结果中出现一次,则不必使用正则表达式:

 item.description.replace(word, '' + word + ''); 

DEMO