Better way to parse JSON?

Hi,

in a previous post I ask how to find all global variable and it's works perfectly. (List of all global)

the JSON i receive is like this :

{
    "payload": [
        {
            "maison/bureau/temperature": "26.30"
        },
        {
            "maison/bureau/humidity": "57.00"
        },
        {
            "maison/bureau/consigne": 16
        }
    ],
    "topic": "uibuilder",
    "_msgid": "293c262c7209e491",
    "count": 3
}

Now, I need to use thoses variables in the uibuilder side.
I make a function like this :

var humidite;
var temperature;

function variables(json) {
    for (i=0;i<json.count;i++){
        if (typeof json.payload[i]["maison/bureau/temperature"]  === 'undefined'){}else{temperature = json.payload[i]["maison/bureau/temperature"]}
        if (typeof json.payload[i]["maison/bureau/humidity"]  === 'undefined'){}else{humidite = json.payload[i]["maison/bureau/humidity"]}
        }
}

window.onload = function() {
    // Start up uibuilder - see the docs for the optional parameters
    uibuilder.start()

    // Listen for incoming messages from Node-RED
    uibuilder.onChange('msg', function(msg){
        console.info('[indexjs:uibuilder.onChange] msg received from Node-RED server:', msg)
variables(msg)
})
}

but I don't think it's the better way to do that.
Anybody have a better method?

Thanks

a couple of things

  1. you receive the msg in uibuilder.onChange and then you call variables(msg) and pass the whole msg object to it. Your function runs and then you try to loop through json .. but json is an object.
    You should have called variables with the msg.payload ... variables(msg.payload)
    Payload is an array and you can loop through it.

  2. for (i=0;i<json.count;i++) count ? shouldnt that be json.length ?

  3. is a loop even necessary just to assign 2 variables to their values ?

var humidite;
var temperature;

function variables(json) {
        if (typeof json.payload[0]["maison/bureau/temperature"]  !== 'undefined') {temperature = json.payload[0]["maison/bureau/temperature"]}
        if (typeof json.payload[1]["maison/bureau/humidity"]  !== 'undefined') { humidite = json.payload[1]["maison/bureau/humidity"]}
      
}

ps. that why i recommended in your previous post to save the data in an object instead :wink:
because there are many points of failure, as nothing guaranties you that the array elements will arrive in the same order. Better send an object instead.

It is important in IT to use the correct terms, to avoid confusion. That isn't JSON. JSON is always a string. It is a javascript object.

This post should help to clarify the difference between Javascript objects and JSON.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.