0

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
            }
        });
Omar
  • 786
  • 3
  • 13
  • 34
  • 1
    Why are you using `dataType: "text"`? – SLaks Jun 13 '17 at 17:39
  • 2
    try `json[thekeyvalue]`. Explanation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors – Will Jun 13 '17 at 17:41
  • omg seriously That was it, but when it can't find it, it's sending "undefined" to the success function instead of error. How can I trigger jquery if it doesnt exist. – Omar Jun 13 '17 at 17:45
  • Something like this: `if (typeof json[thekeyvalue] !== 'undefined') { // exists // Do what you want as it exists } else { // Do something when it doesn't. Like show an error. }` – Juan Jun 13 '17 at 17:49

1 Answers1

0

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 "";
        }
    });
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
  • Seems like it won't parse "undefined" When it comes back "undefined" I keep getting back an error that says: Uncaught TypeError: Cannot read property 'png' of undefined at Object.success – Omar Jun 13 '17 at 18:15
  • try catch inside the success function worked for me but I wonder if there's a better way: Found here: https://stackoverflow.com/questions/14782232/how-to-avoid-cannot-read-property-of-undefined-errors try{ window.a.b.c }catch(e){ console.log("YO",e) } – Omar Jun 13 '17 at 18:24
  • You can try using `if(json["12F"]])` i.e. an if condition to check if the value is `undefined`. – Hassan Imam Jun 16 '17 at 05:36