How to dynamically create DataTable columns from JSON keys in UiPath C#?

Hi all,

I’m working on a project in UiPath using C# mode, and I’m calling the public API:
:backhand_index_pointing_right: https://randomuser.me/api

This API returns a JSON response like this (simplified):

{
  "results": [
    {
      "name": {
        "title": "Miss",
        "first": "Abby",
        "last": "Oliver"
      }
    }
  ]
}

:white_check_mark: What I want to achieve:

I only want to extract the name object and:

  1. Create DataTable columns dynamically based on the keys inside the name object (title, first, last)
  2. Add a new row with their corresponding values
  3. The solution should be dynamic, so that if the name object has more/less properties in the future, it still works.

I’ve tried this, what should i do next?

Hi @Vhierdy_Hafidz

Select C Sharp in Properties Panel of Invoke Code:

Try the below Invoke Code:

// Input: jsonResponse (string) - your JSON input
// Output: outputTable (DataTable) - your dynamically built DataTable

var nameObj = jObj["results"]?[0]?["name"] as JObject;

outputTable = new DataTable();

if (nameObj != null)
{
    // Create columns dynamically based on name object keys
    foreach (var prop in nameObj.Properties())
    {
        outputTable.Columns.Add(prop.Name, typeof(string));
    }

    // Create a new row and fill values
    var newRow = outputTable.NewRow();
    foreach (var prop in nameObj.Properties())
    {
        newRow[prop.Name] = prop.Value?.ToString();
    }
    outputTable.Rows.Add(newRow);
}

Invoke Code Arguments:

You can remove the entire Multiple Assign activity and try the above code.

Hope it helps!!

we can exploit JSON functionalities and model it flat:

dtResult=

JArray.FromObject(myJObject["results"].Values<JObject>().Select( x=>x["name"].Value<JObject>())).ToObject<DataTable>()

Verification check:

when it is ensured that the JSON will only have one item within the results we can modify the above statement to:

dtResult=

JArray.FromObject( new JObject[1] {myJObject.SelectToken("results.[0].name").Value<JObject>() } ).ToObject<DataTable>()