简体   繁体   中英

Read and parse JSON by variable

I have a value stored as thekeyvalue. In this case "12F" for example. I want to see if it exists in my JSON. If so, I'd like to grab the PNG value. If not, just send a message back

JSON

{
    "Property": "99",
    "12F": {
        "png": "12-74"
    },
    "13F": {
        "png": "12-74"
    }
}

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
            }
        });

This is how your success function should be. Please check.

   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 "";
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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