【问题标题】:How to split JSON values if it contains "Most_Likely"?如果 JSON 值包含“Most_Likely”,如何拆分它?
【发布时间】:2014-12-09 18:27:23
【问题描述】:

我正在尝试解析 JSON 值并解析我需要的内容。

基本上,我只想捕获标记为“Most_Likely”的值。

另外,如果有 OR 语句,我需要将这些值分开。

这是我的尝试,但我遇到了 JS 错误:

for (i = 0; i < obj1.Summary.length; i++) {


for (j in obj1.Summary[i]) {
    
    if (j.indexOf('Most_Likely') && obj1.Summary[i][j].indexOf('|OR|') >= 0){
        var tempvalue = obj1.Summary[i][j].indexOf('Most_Likely').split(" |OR| ");
        attributesvalues.push(tempvalue);
        alert(attributesvalues);
    }
    else{
    //do nothing
    }
    
    
   }

}

//JSON 示例

var obj1 = {
 "Summary" : 
    [
        {
            "host:Most_Likely" : "www.google.com", 
            "host:Indicative" : "www.yahoo.com |OR| www.google.com", 
            "term:Most_Likely" : "cars" |OR| new cars |OR| SUVs, 
            "term:Indicative" : "automatic |OR| Lexus |OR| SUVs |OR| Civic" 
        }
    ]
 };

【问题讨论】:

标签: javascript json parsing


【解决方案1】:

这一行出错

var tempvalue = obj1.Summary[i][j].indexOf('Most_Likely').split(" |OR| ");

indexOf 返回位置(类型号),拆分存在于 String 对象中,这就是您得到错误的原因。

var attributesvalues = [],
    tempvalue;

for (var i = 0; i < obj1.Summary.length; i++) {
  for (var j in obj1.Summary[i]) {
    if (j.indexOf('Most_Likely') >= 0 && obj1.Summary[i][j].indexOf('|OR|') >= 0) {
      tempvalue = obj1.Summary[i][j].split(" |OR| ");
      attributesvalues.push(tempvalue);
    } else { 
    }
  }
}

console.log(attributesvalues);

【讨论】:

    【解决方案2】:

    正如我所写的,我在这里看到了一些潜在的问题。

    1. 您将j.indexOf('Most_Likely') 作为布尔条件的一部分。如果未找到元素,indexOf 返回 -1,这被认为是 truthy。您可能希望将其阅读为 j.indexOf('Most_Likely') !== -1

    2. 在您的示例obj1 中,您对term:Most_Likely 的值是"chars" |OR| new cars |OR| SUVs。在我看来,你过早地终止了你的字符串,导致 JS 想知道,“这都是什么 |OR| 东西?”

    3. 您试图在此行中的一个整数上调用splitobj1.Summary[i][j].indexOf('Most_Likely').split(" |OR| ")。如前所述,indexOf 返回找到项目的索引。如果您从该行中删除 indexOf 位,它可能会执行您想要的操作。

    【讨论】:

    • 另外值得注意的是,你不需要 if 后面的空 else 子句。
    猜你喜欢
    • 1970-01-01
    • 2020-11-14
    • 2021-05-17
    • 2018-01-25
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多