3

I am trying to figure out a way to retrieve a Boolean value from a JSON string retrieved from an ajax query. I can access string and integer values, but any Boolean values are returned to console as undefined.

Here is my script for parsing the ajax return data.

success: function(data){
     let results = jQuery.parseJSON(data);
     var outside = results.outside;
     console.log(outside);
     if(outside){
      console.log("true");
     }
}

and here is an example of my JSON string:

{
    "glossary": "alphabet",
    "store": "Henry",
    "outside": true
}

I can return the string values, but not the Boolean value of "outside". I know it is being retrieved by the ajax call because in testing I print data to the console and I can see its value as true.

5
  • 1
    How are you trying to use the boolean? Could you post a quick snippet of where and how you are doing that? Commented Apr 25, 2019 at 18:48
  • 1
    How are you accessing the data? Also, what does Object.keys(results) say? Commented Apr 25, 2019 at 18:48
  • 1
    If you're trying to access the value from outside the "success" callback, well that's your problem. Commented Apr 25, 2019 at 18:50
  • Works on my box: jsfiddle.net/o4p7vb5k/1 with both the native JSON.parse and jQuery's parseJSON methods. Commented Apr 25, 2019 at 18:52
  • @MichaelPlatt I have added briefly how the boolean is used, it basically satisfies an if statement. Commented Apr 25, 2019 at 18:57

2 Answers 2

2

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.

from: http://api.jquery.com/jquery.parsejson/

so, you need to use: JSON.parse method https://www.w3schools.com/js/js_json_parse.asp

Sign up to request clarification or add additional context in comments.

Comments

1

let results = JSON.parse(data);, No?

3 Comments

jQuery has a JSON parser API. If it didn't, the OP would have seen an error from that.
this is correct, $.parseJSON is deprecated from jQuery 3.0.
This assumes that OP is using the latest jQuery version (which is not clearly stated), and even if they were, deprecated just means it should be avoided to use the function anymore, it's not yet removed from the code base but will be in a future update. Otherwise, an error would be thrown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.