Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.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
Javascript 通过变量读取和解析JSON_Javascript_Jquery_Json - Fatal编程技术网

Javascript 通过变量读取和解析JSON

Javascript 通过变量读取和解析JSON,javascript,jquery,json,Javascript,Jquery,Json,我将一个值存储为keyValue。在本例中,以“12F”为例。我想看看它是否存在于我的JSON中。如果是这样,我想获取PNG值。如果没有,就发一条信息回来 JSON JQUERY var sourceurl = '../floorplan-data.json'; var thekeyvalue = $("#finalkey").text(); //start ajax request $.ajax({ url: source

我将一个值存储为keyValue。在本例中,以“12F”为例。我想看看它是否存在于我的JSON中。如果是这样,我想获取PNG值。如果没有,就发一条信息回来

JSON

JQUERY

var sourceurl = '../floorplan-data.json';
        var thekeyvalue = $("#finalkey").text();
        //start ajax request
        $.ajax({
            url: sourceurl,
            //force to handle it as text
            dataType: "text",
            error: 
           function(){
              //error
           },
            success: function(data) {
              var json = $.parseJSON(data);
              console.log(json.thekeyvalue); //having trouble here
            }
        });

这就是你成功的方式。请查收

   var sourceurl = '../floorplan-data.json';
    var thekeyvalue = $("#finalkey").text();
    //start ajax request
    $.ajax({
        url: sourceurl,
        //force to handle it as text
        dataType: "text",
        error: 
       function(){
          //error
       },
        success: function(data) {
          var json = $.parseJSON(data);
          if(json["12F"]]) 
              return json["12F"].png;
          else 
              return "";
        }
    });

为什么要使用
数据类型:“text”
?请尝试
json[thekeyvalue]
。说明:omg说真的就是这样,但当它找不到它时,它会向success函数发送“undefined”,而不是error。如果jquery不存在,我如何触发它。类似这样:
if(json的类型[thekeyvalue]!='undefined'){//exists//Do you want as it exists}否则{//Do this when this not.like show a error.}
当返回“undefined”时,它似乎不会解析“undefined”我一直收到一个错误,上面写着:uncaughttypeerror:cannotreadproperty'png'of undefined at Object.successtry catch在success函数中对我有效,但我想知道是否有更好的方法:在这里找到:try{window.a.b.c}catch(e){console.log(“YO”,e)}你可以尝试使用
if(json[“12F”])
即一个if条件,用于检查值是否
未定义
   var sourceurl = '../floorplan-data.json';
    var thekeyvalue = $("#finalkey").text();
    //start ajax request
    $.ajax({
        url: sourceurl,
        //force to handle it as text
        dataType: "text",
        error: 
       function(){
          //error
       },
        success: function(data) {
          var json = $.parseJSON(data);
          if(json["12F"]]) 
              return json["12F"].png;
          else 
              return "";
        }
    });