-1

I've seen many post on how to turn a Javascript string into a JSON, but not any that suggest how to turn a JSON object into a javascript string.

The code snippet below returns the correct values when they are displayed in the on the javascript console, however, when I attempt to do an string to JSON.element comparison, it fails.

Here's the JSON that's being returned by the URL request.

{
  "id": "1e003033",
  "name": "camera",
  "last_app": null,
  "last_ip_address": "192.168.0.27",
  "last_heard": "2016-08-27T14:22:49.762Z",
  "product_id": 6,
  "connected": true,
  "platform_id": 6,
  "cellular": false,
  "status": "normal",
  "pinned_build_target": "0.5.2",
  "variables": {
    "lonlat": "string",
    "speedmph": "string",
    "sats": "string"
  },
  "functions": []
}

Here's the code snippet:

       requestURL_O = "https://api.spark.io/v1/devices/" + deviceID + "/?access_token=" + accessToken;
       $.getJSON(requestURL_O, function(jonline){
                   console.log(jonline.connected);
                   jstr = jonline.connected;
                   dt_str = jonline.last_heard;
                   console.log(jstr);
                   if (jstr == "true"){
                     online_status = true;
                     console.log("equal = TRUE");
                   }
                   else { 
                    online_status = false;
                    jstr = jonline.last_heard;
                    console.log(jonline.last_heard);
                    console.log("equal = FALSE");
                  }
       });

console.log(jstr) is returned at true. console.log(jonline.connected) is returned as true.

The comparison below always falls through to the else.

if (online_status) {  
  document.getElementById("temp").innerHTML = "Online";
  document.getElementById("tstamp").innerHTML = "Last heard from (GMT) Date/Time          -> " + jstr;
}
else {
  document.getElementById("temp").innerHTML = "NOT Online";
  document.getElementById("tstamp").innerHTML = "Last heard from (GMT) Date/Time          -> " + dt_str;
}

I'm fairly certain the JSON object needs to be converted to a javascript string, but I've not been able to locate the method that will do that. All the searching I've found talks about going from javascript to JSON.

Thanks in advance for any assistance!

user3254596
  • 43
  • 1
  • 5
  • 1
    JSON.stringify()? – Mykola Borysyuk Aug 27 '16 at 15:06
  • Possible duplicate of [Convert JS object to JSON string](http://stackoverflow.com/questions/4162749/convert-js-object-to-json-string) – Aman Rawat Aug 27 '16 at 15:08
  • `$.getJSON` already converts the string that was sended by the server in JSON format into a JavaScript object. – t.niese Aug 27 '16 at 15:09
  • 3
    @AmanRawat Why do you think it's a duplicate of that? Did you read the answer someone posted? – Barmar Aug 27 '16 at 15:09
  • @Barmar As per the question specifies **"I'm fairly certain the JSON object needs to be converted to a javascript string, but I've not been able to locate the method that will do that."**. So that's why i marked it as a duplicate. – Aman Rawat Aug 27 '16 at 15:14
  • 3
    @AmanRawat But he was *wrong* about that. He doesn't need to convert it to a Javascript string. So it's not a duplicate. – Barmar Aug 27 '16 at 15:14
  • 3
    @AmanRawat How would converting it to a Javascript string solve the problem that `jstr = jonline.connect;` isn't working? – Barmar Aug 27 '16 at 15:15
  • 2
    @Barmar NO it can't, but the question title and description mislead me to this conclusion. Although i get it now thanks for pointing it out :) – Aman Rawat Aug 27 '16 at 15:19

2 Answers2

5

jonline.connect != jonline.connected

Change jstr = jonline.connect; to jstr = jonline.connected;

You don't need to convert the JSON String into a JS object, as jQuery's $.getJSON already automatically converts that.

Also, squint pointed out in a comment below that you're also comparing the boolean true from the object to a string "true". Those are not the same thing.

Change if (jstr == "true") { to if (jstr == true) {

This is because you have the line "connected": true in your json, not "connected": "true".

As per your comment, it seems another issue is that the code you're using to set the html contents based on your result is doing the comparison before your JSON callback is executed. Everything you append after $.getJSON() will happen instantaniously, even if the json hasn't loaded yet, beucase it is an asynchronous function.

You can either add your code right within the callback:

if (jstr == "true") {
   online_status = true;
   document.getElementById("temp").innerHTML = "Online";
   document.getElementById("tstamp").innerHTML = "Last heard from (GMT) Date/Time          -> " + jstr;
} else { 
   online_status = false;
   jstr = jonline.last_heard;

   document.getElementById("temp").innerHTML = "NOT Online";
   document.getElementById("tstamp").innerHTML = "Last heard from (GMT) Date/Time          -> " + dt_str;
}

Or if online_status is a variable you can refer to from without your function, which it currently isn't, if I correctly understood your comment, you could create a function with your online_status comparison and call it in your $.getJSON callback, after settings the values.

Stefan Wittwer
  • 783
  • 6
  • 16
  • 1
    That's part of the problem but not all of it. The OP is comparing `jstr == "true"`, which will compare a boolean to a string, yielding an incorrect result when `jstr` is `true`. –  Aug 27 '16 at 15:19
  • I've updated the code snippets, and fixed the typo and changed the If (jstr == "true") to if (jstr == true) and now the online_status var is getting set to true, however, the if (online_status == true) fails through to the else every time now. console.log says it equals true. – user3254596 Aug 27 '16 at 15:31
  • @user3254596 Then it's probably scope issue. Where do you have online_status initially declared? – Stefan Wittwer Aug 27 '16 at 15:33
  • I think the problem might be that the if(online_status) is being executed before the $.getJSON(... has completed. console.log shows both online_status and jstr to be undefined. They are both vars of the function that the $.getJSON( is part of, so they should be as least known to everything in that function. – user3254596 Aug 27 '16 at 15:39
  • 1
    @user3254596 Yea that's right, any code you append after the $.getJSON() method will execute before the JSON is returned, because it is an asynchronous function. Put the if (online_status) right inside the $.getJSON callback method, although why not set ''document.getElementById("temp").innerHTML" right inside your "if (jstr == true){" if online_status is only available within that function anyway? – Stefan Wittwer Aug 27 '16 at 15:42
  • 2
    @user3254596: [Read this Q&A](http://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron). This gets asked about multiple times a day. –  Aug 27 '16 at 16:52
-1

var x={"city":"New York"};
JSON.stringify(x); // '{"city":"New York"}'

This works

Sagar Munjal
  • 762
  • 11
  • 12