Page 1 of 1
Nested JSON or XML from multiple arrays
Posted: 12 Dec 2017, 19:44
by Gsand
Is there a way to create a nested JSON or XML from a couple of Arrays?
For example one array is [Name] = Bob, Jim, Berry
and another is [Age] = 42, 25, 37
and convert that into something like
Code: Select all
{
"person": [
{
"Name": "Bob",
"Age": "42"
},
{
"Name": "Jim",
"Age": "25"
},
{
"Name": "Berry",
"Age": "37"
}
]
}
Thanks all
Re: Nested JSON or XML from multiple arrays
Posted: 13 Dec 2017, 08:21
by lerou
Hi,
write a C# script and use json serialization.
cheers,
rou
Re: Nested JSON or XML from multiple arrays
Posted: 13 Dec 2017, 15:41
by stephen
Hi Greg,
like Rou already mentioned, it is best solved with a Script Node. You can start with something like the attached code.
It can replace the Validate Method of a Script.
This uses the JavaScriptSerializer class of the .NET Framework that is located in the System.Web.Extensions assembly - add that to the GAC Assemblies of the Script.
The idea is to build a structure of Lists or Dictionaries with help classes as needed for the wanted JSON-Structure. In this case it is a List of Person-Objects whose class is declared in the Script.
A sample scene is attached (created in Version 5.3.5).
Best
Stephen
Code: Select all
// This Method is called if an input property has changed its value
public override void Validate()
{
// Remember: set changed to true if any of the output
// properties has been changed, see Generate()
var json = new System.Web.Script.Serialization.JavaScriptSerializer();
var personlist = new System.Collections.Generic.List<Person>();
for(int i = 0; i < Math.Min(IntArray1.Length, StringArray1.Length); i++)
{
personlist.Add(new Person()
{Age = IntArray1[i],
Name = StringArray1[i]
});
}
String1 = json.Serialize(personlist);
changed = true;
}
private class Person
{
public int Age {get;set;}
public string Name{get;set;}
}
Sample Input:
Code: Select all
IntegerArray1: "21, 22, 20, 12"
StringArray1: "Ben, Boy, Bill, Bruce"
Output of the Script:
Code: Select all
[{"Age":21,"Name":"Ben"},{"Age":22,"Name":"Boy"},{"Age":20,"Name":"Bill"},{"Age":12,"Name":"Bruce"}]