Array to Json Object

Hey there,
I want to convert an array to a Json object. I've tried many ways but i didn't get the format I want!
I want to get the following result:
payload: " {"Val1" : 10, "Val2" : 11, "Val3: 12} "

Plus, I have a subflow that returns a value, how can I put this value in a Json object, say "Value1" : 20 ?

thank you,

Hi @jackie7

Sorry to nitpick but Json object is not a thing.
JSON is a string representation of a JavaScript object.

Ok, enough of that :slight_smile:

Use a function node, loop through the elements & add properties to an object...

  var arr = msg.payload; // get the array
  var rv = {};// create a new empty object
  for (var i = 0; i < arr.length; ++i) {
    let key = "Val"+(i+1); //built a key 
    rv[key] = arr[i]; // set value in New object
  }
  msg.payload = nv;
  return msg;

There are other, more modern/compact ways to achieve this but I kept it simple for clarity.

Disclaimer: the above code is untested/off the top of my head. :innocent:

1 Like

Thank you for the clarification!
I'm able to parse the array and get the values but I want to assign names to them, each value has a different name. how can I change their names from Val1 Val2...?

unless you tell me what they are I cannot really help. an array is just a group of values.

If you know which element is which item & they are always in the same place & there are always a fixed number of elements in the array, you can simply set them manually in the object.

However, there may be a better solution - we should look at that first.

Where does this array come from? can you show me how this array is generated?

You would need to list the names

var names = ["name1","another_name","any_anme_you_wish"];// list of names
var hold_obj = {};// `temp object
names.forEach ((v,i) => hold_obj[v] = msg.payload[i]) //loop through names and add to object
msg.payload = hold_obj; // move back to payload
return msg;

assuming the array is in msg.payload.

That was helpful, thank you very much!!

This was solved, Thank you for your help!

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