Website returns "var temp = "24";" How to parse such a string into json

I'm trying to pull data out of the official Canadian weather service website. There is a script used on the site that returns the values used by the rest of the scripts to format the page as a javascript variable declaration.

var obTemperature = "24";
var obIconCode = "29";
var obCondition = "";
var obWindDir = "SE";
var obWindSpeed = "10";
var obWindGust = "";
var obWindChill = "";
var obHumidex = "28";

What is the best way to turn this into a json object I can more easily use in node red ? I was thinking it could be sent into a function but don't know how to turn such text into javascript that is executed ?

I'm aware of openweathermap, wunderground etc. but I'd like to use this.

Can you post the debug output so we can see the actual output.

I would use a function node (maybe jsonata would work too -- it's rather powerful -- but I don't know much about jsonata).

If you've received the following declarations as a string, I would do a series of replace() on the string. You can use regex which is of great help.

  • replace all the var with " (quote)
data = data.replace(/var/g,'"');
  • replace all the ; characters with , (comma)
data = data.replace(/;/g, ",");
  • replace all the = (with leading space) characters with ": (a quote AND a colon)
data = data.replace(/ =/g, '":');
  • now we must remove all the quotes surrounding numbers (but not the ones surrounding strings)
data = data.replace(/"(\d+)"/g, "$1");

or maybe, if you have floating numbers you can use this one instead:

data = data.replace(/"([\d.]+)"/g, "$1");

We now have something like this

 "obTemperature": 24,
 "obIconCode": 29,
 "obCondition": "" ,
 "obWindDir": "SE",
 "obWindSpeed": 10,
 "obWindGust": "" ,
 "obWindChill": "" ,
 "obHumidex": 28,
  • remove that last comma with
data = data.substr(0, data.lastIndexOf(","))
  • add a leading { and trailing }
data = "{" + data + "}";
  • and now convert to json
let json = JSON.parse(data);

I think I got it all :wink:

1 Like

Thanks for the reply, the last line was really the conceptual stumbling block for me, the grep expressions doesn't seem to work quite right, but that's something I can work on. Thanks again!