How to create a json using loop

hi i am new to js,
i have an json loop like:

var sammy = {
    "device": [{
    "imsi"      :  msg.payload.data.devices[0].imsi,
    "rg_id"     :  msg.payload.data.devices[0].rg_id,
    "id"        :  msg.payload.data.devices[0].id 
    },
    {
    "imsi"      :  msg.payload.data.devices[1].imsi,
    "rg_id"     :  msg.payload.data.devices[1].rg_id,
    "id"        :  msg.payload.data.devices[1].id 
    }]
}

how can i use a loop to create this(Json)?
thanks

Take a look at JSONata and a change node:


If you set a change node to the mode that looks like a capital J with a colon, you can write JSONata queries in it.

Not sure what the final goal is but looking at your example you could probably just do

var sammy = {
     "device": msg.payload.data.devices
}

Otherwise look at the map() function (it exists for both javascript and JSONata)

I don't know much JS but I think the correct term is that you have a Javascript object called sammy

1 Like

if yuo see sammy structure, it's sammy = {device: [[...], [...]]}
so you can use .push() to create the array

var sammydata = {device:[]};
for (var i = 0; i<2; i++) {
sammydata = {imsi: ...., rg_id:...,id:...};
sammy.device.push(sammydata);
}

you can push sammydata into sammy.device array

1 Like

hi thanks for help.
i will make my question clear
i have some sensor working ....
and i am working on the API...
to get the info.
sorry since my flow is too large to post , so i post only some info here:

Here is the info get from the API


1)
since i dont know how many device exist .
so i need a loop(?) to get the grab the data..
which is the imsi , rg_id
2) and i need to get the data to form another JSON object so that to pass to the DB.

thanks if anyone can help
thanks

Start with a Change node to Move msg.payload.data/devices to msg.payload (assuming the object you showed is in msg.payload, it is off the top of the screen so not certain). Feed that into a debug node to make sure the devices array is now in msg.payload. When that works feed it into a Split node, which will split the array into messages, one device record per message. Again use a debug node to check you now see one message for each element in the array. Then you can do what you want with those messages.
If you have not already done so then read the node red docs page Working with Messages which has a lot of useful information.

1 Like

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