Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/cmake/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
我可以在$.getJSON函数中使用递归JavaScript函数吗?_Javascript_Jquery_Json_Regex_Recursion - Fatal编程技术网

我可以在$.getJSON函数中使用递归JavaScript函数吗?

我可以在$.getJSON函数中使用递归JavaScript函数吗?,javascript,jquery,json,regex,recursion,Javascript,Jquery,Json,Regex,Recursion,我有一个深度可变的JSON文档。例如: [ { "type": "firsttype", "text": { "id": "content" } } ] 我试图做的是检索某些键的值,比如text。因为我不知道这些键可能出现在.JSON中的什么位置,所以我需要使用递归函数。然后,我尝试在HTML文件中显示这些键和值 我在这里有一个初步尝试: $.getJSON("file.json", function ge

我有一个深度可变的JSON文档。例如:

[
    {
        "type": "firsttype",
        "text": {
            "id": "content"
        }
    }
]
我试图做的是检索某些键的值,比如
text
。因为我不知道这些键可能出现在.JSON中的什么位置,所以我需要使用递归函数。然后,我尝试在HTML文件中显示这些键和值

我在这里有一个初步尝试:

$.getJSON("file.json", function getText (oValue, sKey) {
    links = [];
    if (typeof oValue == "object" || typeof oValue == "array") {
        for (i in oValue) {
            getText (oValue [i], i);
        }
    } else {
        links.push ( "<li id='" + oValue + "'>" + sKey + "</li>" );
    }

    $( "<ul/>", {
        "class": "my-new-list",
        html: links.join( "" )
    }).appendTo( "body" );
});
$.getJSON(“file.json”,函数getText(oValue,sKey){
链接=[];
if(typeof oValue==“object”| | typeof oValue==“array”){
对于(i为椭圆形){
getText(oValue[i],i);
}
}否则{
links.push(“
  • “+sKey+”
  • ”; } $(“
      ”{ “类”:“我的新列表”, html:links.join(“”) }).附于(“主体”); });
    当我本地或远程加载页面时,或者在
    python-msimplehttpserver
    上加载页面时,我没有收到任何错误,页面上也没有任何内容。我做错了什么?我已经在
    $.getJSON
    调用中包含了所有的JS,因此不会出现异步问题


    在将来,我还希望包含一个regexp检查,以便可以使用特定字符串提取值,例如
    /http/
    。最好的方法是什么?

    我认为您的错误在于声明变量链接: 我想它一定在递归函数之外。 在函数内部,每次都会重新初始化它

    var links = [];
    
    $.getJSON("file.json", function getText (oValue, sKey) {
    
             if (typeof oValue == "object" || typeof oValue == "array") {
                for (i in oValue) {
                    getText (oValue [i], i);
                    }
             } else {
                    links.push ( "<li id='" + oValue + "'>" + sKey + "</li>" );
               }
    
               $( "<ul/>", {
                           "class": "my-new-list",
                           html: links.join( "" )
               }).appendTo( "body" );
    });
    
    var-links=[];
    $.getJSON(“file.json”,函数getText(oValue,sKey){
    if(typeof oValue==“object”| | typeof oValue==“array”){
    对于(i为椭圆形){
    getText(oValue[i],i);
    }
    }否则{
    links.push(“
  • “+sKey+”
  • ”; } $(“
      ”{ “类”:“我的新列表”, html:links.join(“”) }).附于(“主体”); });
    尝试将函数定义移到事件处理程序之外:

     function getText (links, oValue, sKey) {
    
    
             if (typeof oValue == "object" || typeof oValue == "array") {
                for (i in oValue) {
                    getText (links, oValue [i], i);
                    }
             } else {
                 if(oValue && sKey)
                    links.push ( "<li id='" + oValue + "'>" + sKey + "</li>" );
             }
    
               $( "<ul/>", {
                           "class": "my-new-list",
                           html: links.join( "" )
               }).appendTo( "body" );
    };
    
    $.getJSON("file.json", function(data, success){
      var links = [];  
    
      getText (links, data, 0);
    });
    
    函数getText(links、oValue、sKey){ if(typeof oValue==“object”| | typeof oValue==“array”){ 对于(i为椭圆形){ getText(links,oValue[i],i); } }否则{ if(oValue&&sKey) links.push(“
  • “+sKey+”
  • ”; } $(“
      ”{ “类”:“我的新列表”, html:links.join(“”) }).附于(“主体”); }; $.getJSON(“file.json”,函数(数据,成功){ var-links=[]; getText(链接,数据,0); }); 如果有错误,请随意编辑

      其目的是将links数组传递给递归函数,避免将命名函数定义与getJSON混淆,至少为了清楚起见,并确保可以传递初始化的sKey。

      可以,但在您的情况下可能不应该 您可以将命名函数作为回调函数传递—这对递归很有用(请参见:,Ben Nadel)—但在您的情况下,您可能不应该这样做

      根据您的示例,在调用递归函数之前和之后,您需要做一些事情。这些事情,比如声明变量和向主体追加元素,需要在递归之外发生[一次]

      因此,传递一个匿名函数作为包含递归函数定义的回调函数,并根据需要调用它

      在本例中,您需要为JSON响应数组中返回的每个对象调用它。因此,您也可以将其放入迭代器中。这里,为了方便起见,我使用了jQuery的
      $.each()

      发出JSON请求的函数*/ 函数dojson(){ /*开始重写OP的示例代码*/ $.getJSON('file.json',函数(json){ var-links=[]; 函数getText(key,val){ if(typeof val==“object”| typeof val==“array”){ 用于(val中的i){ getText(i,val[i]); } }否则{ links.push(“
    • “+key+”(“+val+”)
    • ”); } } $.each(json,函数(key,val){ getText(key,val); }); $(“
        ”{ “类”:“我的新列表”, “html”:links.join(“”) }).附于(“主体”); }); /*结束示例代码的重写*/ } /*以下不是示例的一部分, //它只是用来模拟服务器响应*/ /*开始单元测试*/ //创建闭包以返回伪函数和伪响应 函数json_响应(响应){ 返回函数(url,成功){ 成功(回应); }; } //使用伪函数和伪响应重写$.getJSON $.getJSON=json\u响应( //“file.json”的模拟内容 $.parseJSON( '[' + ' {' +“类型”:“firsttype” +““案文”:{” +“id”:“内容” + ' }' + ' },' + ' {' +“类型”:“第二种类型” +““案文”:{” +““id”:“其他”” + ' }' + ' }' + ']' ) ); dojson(); /*终端单元测试*/
        <代码> <代码> > p>因为其他的答案覆盖了大部分你应该考虑的事情,我想我会为你的实际问题发布一个解决方案。p> 您希望遍历任意JSON并搜索特定键,并且可能对其值有一个条件。然后,您希望返回指定键的所有值(如果指定,则通过条件)

        假设您拥有以下json:

        {
            "hello": "some text",
            "object": {
                "key1": "hello!",
                "key2": "Bye!"
            },
            "array": [{
                "some_key1": "blah blah blah",
                "some_key2": 24
            }, {
                "some_key1": "ghiojd",
                "some_key2": 13
            }],
            "numeric_array": [2, 3, 4, 5]
        }
        
        此代码段将在上面的json中搜索其值以
        blah开头的
        some_key1

        函数regexpConditionFactory(regex){
        返回函数(值){return regex.test(值);};
        }
        函数searchObjectForKey(对象、键、条件、结果){
        如果($.isPlainObject(obj)){
        if(对象hasOwnProperty(键)){
        if(!condition | |($.isFunction(condition)和&condition(obj[key]))
        结果.推送(obj[键]);
        }