JSON in Frends

JSON is utilized a lot in Frends Processes.

A lot of the data being handled in Frends Processes is stored and handled in JSON format. Frends internally handles all data transfers as JSON objects, or JSON objects serialized into a string, using Newtonsoft JSON library for C#. Because of the native support for JSON, a lot of functionality in Frends makes more sense if JSON is used.

JSON Objects

JSON Objects are object representations of JSON data. Each key-value pair in JSON data is stored as properties and values of the object. In Frends, the NewtonSoft.Json library is used to create objects from JSON data. In addition to storing JSON data in objects, you also get the benefits of Object-Oriented Programming, since JSON objects inherit methods and properties from the Object class. Objects also enable different ways of processing data efficiently compared to raw JSON data. In this module we will be looking into most used JSON objects in Frends.

JObject

The JObject class is an object representation of a single JSON object. This object contains properties which represent JSON keys. These properties have values which are representation of JSON key values. Lets take a look at the following example JSON data from a Frends C# Expression Element.

Example of creating a string variable containing JSON.

Here we have JSON data which has three keys: FirstName, SecondName and Age with values Erik, Example and 20. We save this value into a variable named "json". Behind the scenes this is a JSON string.

We can then parse this JSON string to a JObject in two ways: using a ConvertJsonStringToJToken Task or the static JObject class method Parse. With a ConvertJsonStringToJToken Task you can pass the JSON string to the Task as a parameter and the result of the Task will be a JToken, which is a parent of the JObject class and behaves in mostly the same way as a JObject.

Converting the string into JSON object allows accessing the properties easily.

The second way is to use the static method JObject.Parse() in a C# Assign Variable shape, in which you pass the JSON string as a parameter. You can then save the created JObject to a variable.

Parse method is alternative to the Task.

After creating the object, we can access the values, as with any other object, using dot notation.

Accessing JObject properties is done using dot notation.

Sometimes the JSON data contains special characters in the keys, such as whitespaces or slashes, which do not transform into object properties very well since they are illegal characters. In these cases, you can use square brackets to access the data.

Here is an example JSON data which contains a key named "Home Address".

Example JSON string containing a property with space in the name.

Since the key contains a whitespace, you cannot use dot notation to access that data. You can however use brackets to access that key. After you have parsed the data using a ConvertJsonStringToJToken Task or the JObject.Parse method you can access the data using square brackets as shown below.

Properties of JObject can also be accessed using indexing.

JArray

Sometimes the JSON data contains multiple objects that we need to handle. Lets say that we would have some JSON data containing multiple person objects that we processed in the example above. Below is an example of such JSON data, which we save to a variable.

Example of array in JSON.

We can then parse the JSON data into a JObject using a ConvertJsonStringToJToken Task in the same way that we did above with the single piece of JSON data. The JObject.Parse method will not work, since the data is not a single piece of JSON data, but an array containing multiple JSON data entries. Hence, we need to use the JArray.Parse method to create a JArray from the data.

Arrays can be parsed into JArray objects using same methods as JObjects.

We can then access each of the values in the JArray in the same way as with any other array, using indices. You can think of JArray as basically an array of objects.

JArrays work almost identically to standard arrays.

Since a JArray is basically an array of objects, we can also iterate the array using a Foreach shape. Below is an example of a Foreach shape's parameters, in which we iterate through the JArray that we created before and we save each of the values into a variable named "singleJsonData" in each iteration.

JArrays can be iterated over with Foreach shape.

We can then access the data of each JObject in the JArray in the same way as we accessed the data in the above JObject example, using dot notation.

When iterated, each element can considered to be a JObject.

From object to JSON string

After creating a JObject or JArray, and processing the data, you might want to transform the object back to a JSON string so you are able to use the data in some other shape, such as in a HTTP Request Task or a CSV Task. This can be easily achieved by calling the JToken.ToString method. Since both JObject and JArray inherit the JToken class, the ToString method is available in both classes. The method overrides the Object class' ToString method so that the method call will return a JSON string representation of the data stored in the object instead of information about the object itself.

Below is an example of the data which is produced by the ToString method call.

Example of how Frends shows JArray and JObject data in the UI.

Object initialization

When creating objects in Frends using C#, at least the following methods are available and can be recommended to be used.

Standard JObject initialization

The standard method to initialize JObjects uses square brackets. Compared to the methods explained next, this may be slightly more performant, but slower to write.

{
    JObject obj = new JObject {
        ["Name"] = "Test Person",
        ["Age"] = 35,
        ["ID"] = System.Guid.NewGuid()
    };
}

Anonymous objects for JObject initialization

When creating general objects for storing data for your use case, JObjects and JArrays are generally the recommended storage type due to native support for the Newtonsoft library.

In order to initialize a JObject, anonymous object is a compact method for doing so:

{
    JObject obj = JObject.FromObject(new {
        Name = "Test Person",
        Age = "35",
        ID = System.Guid.NewGuid()
    });
}

Collection initialization

In order to initialize collections, such as Lists and JArrays, collection initialization can be used.

{
    List<string> list = new List<string> { "Bananas", "Apples", "Kiwis" };
    
    JArray arr = new JArray { "Bananas", "Apples", "Kiwis" };
    
    // Converting from a list is also possible
    JArray arr2 = JArray.FromObject(list);
}

JObjects can also be initialized using collection initialization, because they implement the same interface as dictionaries.

{
    JObject obj = new JObject {
        { "Name", "Test Person" },
        { "Age", 35 },
        { "ID", System.Guid.NewGuid() }
    };
    
    Dictionary<string, object> dict = new Dictionary<string, object> {
        { "Name", "Test Person" },
        { "Age", 35 },
        { "ID", System.Guid.NewGuid() }
    };
    
    // Converting from a dictionary is also possible
    JObject obj2 = JObject.FromObject(dict);
}

Accessing object fields

Instead of directly creating the containers using initializers, declaring an empty object first and building on top of it is also possible.

{
    JObject obj = new JObject();
    obj["Name"] = "Test Person";
    obj.Add("Age", 35);
    obj.Add(new JProperty("ID", System.Guid.NewGuid()));
    
    // Dynamic JObject allows using dot notation
    dynamic obj2 = new JObject();
    obj.Name = "Another Person";
    
    JArray arr = new JArray();
    arr.Add("Apples");
    arr.Add("Bananas");
    arr[2] = "Kiwis";
}

LINQ for JSON

LINQ, or Language Integrated Query, is a method to query data using familiar syntax from query languages, such as SQL. You can use LINQ to query lists or arrays to find data matching rules or patterns you want. In addition to iterable data types, you can also use LINQ to query data in JObject.

In order to use LINQ, we first need the data to be in JObject or JArray data type, instead of string or other generic types.

If we have the list of people from earlier, we can use the following syntax to make queries to the content.

{
    JArray peopleArray = JArray.Parse(#var.peopleJsonString);
    
    // Select all who are aged below 40
    JArray youngsters = from people 
                        in peopleArray 
                        where (int)people["Age"] < 40 
                        select people;
    
    // Select only IDs for everyone
    JArray ids = from people
                 in peopleArray
                 select people["ID"];
}

Last updated

Was this helpful?