繁体   English   中英

Javascript / jQuery在json中搜索字符串然后运行一个函数

[英]Javascript/jQuery search json for a string then run a function

如果在外部json文件中找到了字符串,则需要运行matchFound()函数。

这是我到目前为止的内容:

function init(){
   $.ajax({
      type: "GET",
      url: "http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=50&callback=?&q=http://www.domain.com/feed.rss",
      dataType: "json",
      success: parseData
   });
}

function parseData(data){
var string_to_find = "Hello World!";
  // look into the data and match the string
}

function matchFound(str, string_to_find){
    alert('Match found in string - '+ str +'\r\n While looking for the string- '+ string_to_find);
    return true;
}

function matchNotFound(){
    alert('No Match found!');   
}

但是我不知道如何解析Json数据并搜索字符串。

我有这个用于XML(感谢@Ohgodwhy),但不确定如何为json转换

function parseXml(xml){
    var string_to_find = "Hello World!";
    $(xml).find('title').each(function(){
        var str = $(this).text();
        if(str.indexOf(string_to_find) > -1){
            if(matchFound(str, string_to_find)){
                return false;   
            }
        }

    });
}

变量内的搜索位置为:responceData>提要>条目> [0]或1或[2]等> contentSnippet

我只需要匹配前10个字符。

如果找到匹配项,则运行funciton matchFound();如果找不到匹配项,则运行功能matchNotFound()

非常感谢对此的任何帮助。

C

在此处输入图片说明

您必须递归地迭代json,然后搜索字符串

function parseData(data){
var string_to_find = "Hello World!";
var is_found = iterate(data , string_to_find);
if(is_found === true){
      matchFound(JSON.stringify(data), string_to_find);
}else{
      matchNotFound(string_to_find);
}
  // look into the data and match the string
}

    function iterate(obj , string_to_find) {
    for(var key in obj) { // iterate, `key` is the property key
        var elem = obj[key]; // `obj[key]` is the value
         console.log(elem, string_to_find);
        if(typeof(elem)=="string" && elem.indexOf(string_to_find)!==-1) { 

            return true;
        }

        if(typeof elem === "object") { // is an object (plain object or array),
                                       // so contains children
           return iterate(elem , string_to_find); // call recursively
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM