How to create dynamic array and pass in Json format

Hello all,

I want to form a dynamic Json string based on values received from a process.
Below is the example:
{
“key1” : “value1”,
“key2” : “value2”,
“key3” : “value3”,
“key4”:[
{
“key4.1” :“value5”,
“key4.2” :“value6”
}

{
  "key4.1" :"value1",
  "key4.2" : "value2"
}

],
“key5” :[
{
“key5.1” : “value9”,
“key5.2” : “value 10”
}

{
   "key5.1" : "value9",
   "key5.2" : "value 10"

}

]
}

Now what I want is the count of array elements for key4 and key 5 is dynamic. Like the process could return me 3,4 items of key4 type. I need to form the json dynamically to include those number of items received.
Is there a way to achieve this?
Any help is appreciated.

Hi, first of all, are you really in StudioX? If you are in Studio, then i see a number of ways to achieve this.

I am using Studio 2020.4.1
I am looking how can I form this json format dynamically. In the sense the number of array items are going to be different for each Transaction. Hence I cannot form a json string and just pass values to it. How do I make the json string form 4 array items for key4 and 3 array items for key5 say example in an Transaction and the next time maybe just 1.

@rinki
find some starter help here:
GenerateJson.xaml (6.1 KB)

1 Like

@ppr: Thank you for the help to get started. :slight_smile:
Now I am stuck at how do I add another array of hobbies to the Hobbies Key.
I did try to invoke another add method to the JObject, however it attempts to add with same name and fails.

You should first build the whole key4 using the arrays and then at the end you add to the json object. You can learn about JObject here: https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_Linq_JObject.htm

Thank you @bcorrea. That helped I created an array of dictionary and passed.

Also I am facing another problem. Sometimes I do not have any data for key4 or key5.
In this case ,I just want to pass the attribute name like:
{
“key1” : “value1”,
“key2” : “value2”,
“key3” : “value3”,
“key4”:[
],
“key5”:[
],
}

How do I handle this scenario, I do not want to pass an empty array.
Just the attribute name and square brackets. Can you please help again.

Is it possible do implement this scenario?

I would say creating the empty array would be the best way, doesnt it work?

@bcorrea: Yes that helped. Thank you so much for all your guidance on this.

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