Identifying that a property's value is an array - c#

I have a JSON file:
{
"abn":"63119059513",
"acn":"119059513",
"business_structure":"Private Company",
"ngr_number":"1231231",
"cbh_number":"1231231",
"main_name":"Brickworks Building Products Pty Ltd",
"trading_name":"Brickworks",
"other_trading_names":"Austral Bricks",
"directors":[
{
"ID":"12114",
"ae_forms_filled_in_ID":"22739",
"name":"John Smith",
"dob":"1983-10-29",
"address_line_1":"123 Fake Street",
"address_line_2":"",
"address_line_city":"Fakeland",
"address_line_postcode":"2000",
"address_line_state":"New South Wales",
"address_line_country":"Australia",
"order_extract_id":null,
"director_found":null,
"drivers_lic":"",
"home_mortgage":"",
"phone":"",
"mobile":"",
"director_email":"",
"director_title":"Mr",
"director_position":"Director",
"dir_pdf_url":null
}
],
}
I want to determine if the value of any property has a structure of an array. The best I can come up with so far is:
StreamReader streamrr = new StreamReader("C:\\temp\\agfarm_example_udate.json", Encoding.UTF8);
string JSON = streamrr.ReadToEnd();
JObject CWFile = JObject.Parse(JSON);
foreach (JProperty property in CWFile.Properties())
{
// Do something
if (property.Value.ToString().Contains("["))
{
// Do something with the array
JArray items = (JArray)CWFile[property.Name];
foreach (JObject o in items.Children<JObject>())
{
foreach (JProperty p in o.Properties())
{
// Do something
}
}
}
}
To determine whether or not a property value has an array, I used the condition:
if (property.Value.ToString().Contains("["))
I'm just wondering if there is a better way of doing this check?

One way to do this is to check the JToken.Type property. Arrays are of type JTokenType.Array:
if (property.Value.Type == JTokenType.Array)
{
var items = (JArray)property.Value;
// Proceed as before.
}
Or, you can just try to cast to JArray:
if (property.Value is JArray)
{
var items = (JArray)property.Value;
// Proceed as before.
}
Both are preferable to checking property.Value.ToString().Contains("[") since a nested property might have an array value, thus causing a bracket to appear somewhere in the ToString() return.
If you want to recursively find every property with an array value, you can introduce an extension method:
public static class JsonExtensions
{
public static IEnumerable<JToken> WalkTokens(this JToken node)
{
if (node == null)
yield break;
yield return node;
foreach (var child in node.Children())
foreach (var childNode in child.WalkTokens())
yield return childNode;
}
}
And then do:
var CWFile = JToken.Parse(JSON)
var arrayProperties = CWFile.WalkTokens().OfType<JProperty>().Where(prop => prop.Value.Type == JTokenType.Array);

public void Traverse(string name, JToken j)
{
foreach (JToken token in j.AsJEnumerable())
if (token.Type == JTokenType.Object)
{
foreach (var pair in token as JObject)
{
string name_ = pair.Key;
JToken child = pair.Value;
Traverse(name, child);
}
}
else if (token.Type == JTokenType.Array) //an array property found
{
foreach (var child in token.Children())
Traverse(((JProperty)j).Name, child);
}
else if (token.Type == JTokenType.Property)
{
var property = token as JProperty; //current level property
Traverse(name, (JContainer)token);
}
else //current level property name & value
{
var nm = "";
var t = "";
if (j is JProperty)
{
nm = ((JProperty)j).Name;
t = Convert.ToString(((JProperty)j).Value);
}
t = Convert.ToString(token);
}
}
Call:
JSON = JObject.Parse(...);
Traverse("", JSON);
To parse and already parsed text for the same reason is not very wise :
if (property.Value.ToString().Contains("["))
Json structure is simple : objects, arrays, properties, values
http://www.json.org/
So array is a wellknown object for json and we are looking for it :
if (token.Type == JTokenType.Array) //an array property

Related

Pick only one record from a JSON array in C#

I'm trying to extract a record from a JSON array but it doesn't seem to work.
Here my code :
DataTable table = ConvertJsonToDatatable(responseBody);
System.Windows.Forms.MessageBox.Show(table.Columns[1].ToString(), "transformation");
The MessageBox isn't showing. I have checked responseBody and the variable isn't empty at all.
Here the structure of this variable (and the JSON array rear)
{
"data":
[
[
1651217520000,
1.0562,
1.0562,
1.056,
1.0561,
0,
0
],
[
1651217580000,
1.0561,
1.0563,
1.0561,
1.0561,
0,
0
]
],
"events": null
}
public static DataTable ConvertJsonToDatatable(string jsonString)
{
var jsonLinq = JObject.Parse(jsonString);
// Find the first array using Linq
var linqArray = jsonLinq.Descendants().Where(x => x is JArray).First();
var jsonArray = new JArray();
foreach (JObject row in linqArray.Children<JObject>())
{
var createRow = new JObject();
foreach (JProperty column in row.Properties())
{
// Only include JValue types
if (column.Value is JValue)
{
createRow.Add(column.Name, column.Value);
}
}
jsonArray.Add(createRow);
}
return JsonConvert.DeserializeObject<DataTable>(jsonArray.ToString());
}
Does anyone have an idea of how to extract/pick one value from this array (which is a string in my code) ?
Have a nice week end everyone and thanks in advance
you have to fix table creating code
public static DataTable ConvertJsonToDatatable(string jsonString)
{
var jsonLinq = JObject.Parse(jsonString);
// Find the first array using Linq
var linqArray = jsonLinq.Descendants().Where(x => x is JArray).First();
//or maybe this would be enough
var linqArray = JObject.Parse(jsonString)["data"];
var jsonArray = new JArray();
foreach (var row in (JArray)linqArray)
{
var createdRow = new JObject();
var i = 0;
foreach (var item in row)
{
i++;
createdRow.Add("col" + i.ToString(), (string)item);
}
jsonArray.Add(createdRow);
}
return jsonArray.ToObject<DataTable>();
}
how to use
DataTable table = ConvertJsonToDatatable(responseBody);
string val = table.Rows[0].Field<string>("col2");
System.Windows.Forms.MessageBox.Show(val, "transformation");
i probably would be marked negative, but i try to explain how it looks like inside. i made example to show tow to get back list of arrays it might visualize for you.
void Main()
{
string json = "{\"data\":[[1651217520000,1.0562,1.0562,1.056,1.0561,0,0],[1651217580000,1.0561,1.0563,1.0561,1.0561,0,0]],\"events\":null}";
var obj = JObject.Parse(json);
foreach (JToken token in obj.FindTokens("data"))
{
foreach (JArray row in JArray.Parse(token.ToString()))
{
row.Dump();
row[0].Dump("first element");
}
}
}
public static class JsonExtensions
{
public static List<JToken> FindTokens(this JToken containerToken, string name)
{
List<JToken> matches = new List<JToken>();
FindTokens(containerToken, name, matches);
return matches;
}
private static void FindTokens(JToken containerToken, string name, List<JToken> matches)
{
if (containerToken.Type == JTokenType.Object)
{
foreach (JProperty child in containerToken.Children<JProperty>())
{
if (child.Name == name)
{
matches.Add(child.Value);
}
FindTokens(child.Value, name, matches);
}
}
else if (containerToken.Type == JTokenType.Array)
{
foreach (JToken child in containerToken.Children())
{
FindTokens(child, name, matches);
}
}
}
}
result would be an array of jarray
so you can build you DataTable rows
.Dump() is a left over from linqpad. Good tool. Same as console.write

How to set values in dynamic JSON

I have an XML file from which dynamically creates a JSON. The last entry in each row should get a value when the JSON is finished.
However when the JSON is finished only the last entry from the last row has a value. I guess its overwriting since I need to recreate every entry for the right JSON structure.
I split the Group of each row and each point is a JObject except the one with "[0]", thats a JArray.
Has anyone an idea how I can avoid overwriting my JObjects? Thanks.
My XML
My JSON
private static void GenerateElement(JObject parent, string path, string value)
{
var parts = path.Split('.');
foreach (var item in parts)
{
var partsCount = parts.Count();
var currentElement = item;
if (partsCount > 1)
{
path = path.Remove(0, item.Length);
if (path.StartsWith("."))
{
path = path.Remove(0, 1);
}
else if (path.EndsWith("."))
{
path = path.Remove(path.Length - 1, 1);
}
parts = path.Split('.');
}
var nextElementPath = path;
var elementArrayName = currentElement;
if (currentElement.IndexOf("[0]") >= 0)
{
elementArrayName = currentElement.Substring(0, currentElement.IndexOf("[0]"));
}
else
{
parent[currentElement] = new JObject();
}
if (partsCount > 1)
{
if (parent[nextElementPath] == null)
{
if (parent[elementArrayName] == null)
{
parent[elementArrayName] = new JArray();
(parent[elementArrayName] as JArray).Add(new JObject());
}
}
if (parent[elementArrayName] is JArray)
{
parent = parent[elementArrayName][0] as JObject;
}
else
{
parent = parent[currentElement] as JObject;
}
}
else
{
parent[currentElement] = value;
}
}
}

Set value in JObject using JsonPath [duplicate]

There is a large JSON file (about a thousand lines). The task is to update existing JProperties, or add new JProperties in a specific location in the structure. The location of the new texts are based on the JToken.Path property. For example, this is the start of the JSON:
"JonSnow": {
"Direwolf": {
"Name": "Ghost",
"Color": "White",
}
}
"DanaerysTargaryen": {
"Dragons": {
"Dragon1": {
"Name": "Drogon",
}
}
"Hair": {
"Color": "White"
}
}
Now the JSON must be updated using a given list of JToken paths and the corresponding values.
The first possibility is, the JProperty corresponding to the path might already exist, in which case the value needs to be updated. I am already successfully implementing this with JToken.Replace().
The second possibility is, the JProperty does not exist yet and needs to be added. For example, I need to add "DanaerysTargaryen.Dragons.Dragon1.Color" with the value "Black".
I know I can use the JSON.Net Add() method, but to use this only the final child token of the path can be missing from the JSON. For example, I can use
JObject ObjToUpdate= JObject.Parse(jsonText);
JObject Dragon = ObjToUpdate["DanaerysTargaryen"]["Dragons"]["Dragon1"] as JObject;
Dragon.Add("Color", "Black"));
But what about if I need to add "JonSnow.Weapon.Type" with the value "Longsword"? Because "Weapon" does not exist yet as a JProperty, and it needs to be added along with "Type" : "Longsword". With each path, it is unknown how much of the path already exists in the JSON. How can this be parameterised?
// from outside source: Dictionary<string, string> PathBasedDict
// key: Jtoken.Path (example: "JonSnow.Weapon.Type")
// value: new text to be added (example: "Longsword")
foreach(KeyValuePair entry in PathBasedDict)
{
string path = entry.Key;
string newText = entry.Value;
if (ObjToUpdate.SelectToken(path) != null)
{ ObjToUpdate.SelectToken(path).Replace(newText); }
else AddToJson(path, newText);
}
What should AddToJson() look like? Iterating through the entire path and checking each possible JProperty to see if it exists, and then adding the rest underneath, seems very cumbersome. Is there a better way to do this? Any Json.NET tricks I am unaware of? I am not even sure how the iteration could be parameterised.
Based on first approach from Heretic Monkey's answer, here is an extension method:
public static class JObjectExtensions
{
/// <summary>
/// Replaces value based on path. New object tokens are created for missing parts of the given path.
/// </summary>
/// <param name="self">Instance to update</param>
/// <param name="path">Dot delimited path of the new value. E.g. 'foo.bar'</param>
/// <param name="value">Value to set.</param>
public static void ReplaceNested(this JObject self, string path, JToken value)
{
if (self is null)
throw new ArgumentNullException(nameof(self));
if (string.IsNullOrEmpty(path))
throw new ArgumentException("Path cannot be null or empty", nameof(path));
var pathParts = path.Split('.');
JToken currentNode = self;
for (int i = 0; i < pathParts.Length; i++)
{
var pathPart = pathParts[i];
var isLast = i == pathParts.Length - 1;
var partNode = currentNode.SelectToken(pathPart);
if (partNode is null)
{
var nodeToAdd = isLast ? value : new JObject();
((JObject)currentNode).Add(pathPart, nodeToAdd);
currentNode = currentNode.SelectToken(pathPart);
}
else
{
currentNode = partNode;
if (isLast)
currentNode.Replace(value);
}
}
}
}
There are a few ways of going about this. Here are two of them.
To go along with your existing code, split the path by '.', then iterate over them. If the path is not there, create it with Add. Otherwise, if we're on the last part of the path, just add the value.
var json = JObject.Parse(#"{""DanaerysTargaryen"":{""Dragons"":{""Dragon1"":{""Name"": ""Drogon""}},""Hair"": {""Color"": ""White""}}}");
var toAdd = "DanaerysTargaryen.Dragons.Dragon1.Color";
var valueToAdd = "Black";
var pathParts = toAdd.Split('.');
JToken node = json;
for (int i = 0; i < pathParts.Length; i++)
{
var pathPart = pathParts[i];
var partNode = node.SelectToken(pathPart);
if (partNode == null && i < pathParts.Length - 1)
{
((JObject)node).Add(pathPart, new JObject());
partNode = node.SelectToken(pathPart);
}
else if (partNode == null && i == pathParts.Length - 1)
{
((JObject)node).Add(pathPart, valueToAdd);
partNode = node.SelectToken(pathPart);
}
node = partNode;
}
Console.WriteLine(json.ToString());
(Example on dotnetfiddle.net)
Otherwise, you could create a separate JObject that represents the node(s) you want to add, then merge them.
var json = JObject.Parse(#"{""DanaerysTargaryen"":{""Dragons"":{""Dragon1"":{""Name"": ""Drogon""}},""Hair"": {""Color"": ""White""}}}");
var toMerge = #"{""DanaerysTargaryen"":{""Dragons"":{""Dragon1"":{""Color"":""Black""}}}}";
var jsonToMerge = JObject.Parse(toMerge);
json.Merge(jsonToMerge);
Console.WriteLine(json.ToString());
(Example on dotnetfiddle.net)

How to add a new JProperty to a JSON based on path?

There is a large JSON file (about a thousand lines). The task is to update existing JProperties, or add new JProperties in a specific location in the structure. The location of the new texts are based on the JToken.Path property. For example, this is the start of the JSON:
"JonSnow": {
"Direwolf": {
"Name": "Ghost",
"Color": "White",
}
}
"DanaerysTargaryen": {
"Dragons": {
"Dragon1": {
"Name": "Drogon",
}
}
"Hair": {
"Color": "White"
}
}
Now the JSON must be updated using a given list of JToken paths and the corresponding values.
The first possibility is, the JProperty corresponding to the path might already exist, in which case the value needs to be updated. I am already successfully implementing this with JToken.Replace().
The second possibility is, the JProperty does not exist yet and needs to be added. For example, I need to add "DanaerysTargaryen.Dragons.Dragon1.Color" with the value "Black".
I know I can use the JSON.Net Add() method, but to use this only the final child token of the path can be missing from the JSON. For example, I can use
JObject ObjToUpdate= JObject.Parse(jsonText);
JObject Dragon = ObjToUpdate["DanaerysTargaryen"]["Dragons"]["Dragon1"] as JObject;
Dragon.Add("Color", "Black"));
But what about if I need to add "JonSnow.Weapon.Type" with the value "Longsword"? Because "Weapon" does not exist yet as a JProperty, and it needs to be added along with "Type" : "Longsword". With each path, it is unknown how much of the path already exists in the JSON. How can this be parameterised?
// from outside source: Dictionary<string, string> PathBasedDict
// key: Jtoken.Path (example: "JonSnow.Weapon.Type")
// value: new text to be added (example: "Longsword")
foreach(KeyValuePair entry in PathBasedDict)
{
string path = entry.Key;
string newText = entry.Value;
if (ObjToUpdate.SelectToken(path) != null)
{ ObjToUpdate.SelectToken(path).Replace(newText); }
else AddToJson(path, newText);
}
What should AddToJson() look like? Iterating through the entire path and checking each possible JProperty to see if it exists, and then adding the rest underneath, seems very cumbersome. Is there a better way to do this? Any Json.NET tricks I am unaware of? I am not even sure how the iteration could be parameterised.
Based on first approach from Heretic Monkey's answer, here is an extension method:
public static class JObjectExtensions
{
/// <summary>
/// Replaces value based on path. New object tokens are created for missing parts of the given path.
/// </summary>
/// <param name="self">Instance to update</param>
/// <param name="path">Dot delimited path of the new value. E.g. 'foo.bar'</param>
/// <param name="value">Value to set.</param>
public static void ReplaceNested(this JObject self, string path, JToken value)
{
if (self is null)
throw new ArgumentNullException(nameof(self));
if (string.IsNullOrEmpty(path))
throw new ArgumentException("Path cannot be null or empty", nameof(path));
var pathParts = path.Split('.');
JToken currentNode = self;
for (int i = 0; i < pathParts.Length; i++)
{
var pathPart = pathParts[i];
var isLast = i == pathParts.Length - 1;
var partNode = currentNode.SelectToken(pathPart);
if (partNode is null)
{
var nodeToAdd = isLast ? value : new JObject();
((JObject)currentNode).Add(pathPart, nodeToAdd);
currentNode = currentNode.SelectToken(pathPart);
}
else
{
currentNode = partNode;
if (isLast)
currentNode.Replace(value);
}
}
}
}
There are a few ways of going about this. Here are two of them.
To go along with your existing code, split the path by '.', then iterate over them. If the path is not there, create it with Add. Otherwise, if we're on the last part of the path, just add the value.
var json = JObject.Parse(#"{""DanaerysTargaryen"":{""Dragons"":{""Dragon1"":{""Name"": ""Drogon""}},""Hair"": {""Color"": ""White""}}}");
var toAdd = "DanaerysTargaryen.Dragons.Dragon1.Color";
var valueToAdd = "Black";
var pathParts = toAdd.Split('.');
JToken node = json;
for (int i = 0; i < pathParts.Length; i++)
{
var pathPart = pathParts[i];
var partNode = node.SelectToken(pathPart);
if (partNode == null && i < pathParts.Length - 1)
{
((JObject)node).Add(pathPart, new JObject());
partNode = node.SelectToken(pathPart);
}
else if (partNode == null && i == pathParts.Length - 1)
{
((JObject)node).Add(pathPart, valueToAdd);
partNode = node.SelectToken(pathPart);
}
node = partNode;
}
Console.WriteLine(json.ToString());
(Example on dotnetfiddle.net)
Otherwise, you could create a separate JObject that represents the node(s) you want to add, then merge them.
var json = JObject.Parse(#"{""DanaerysTargaryen"":{""Dragons"":{""Dragon1"":{""Name"": ""Drogon""}},""Hair"": {""Color"": ""White""}}}");
var toMerge = #"{""DanaerysTargaryen"":{""Dragons"":{""Dragon1"":{""Color"":""Black""}}}}";
var jsonToMerge = JObject.Parse(toMerge);
json.Merge(jsonToMerge);
Console.WriteLine(json.ToString());
(Example on dotnetfiddle.net)

looping through string object dictionary

So, im successfully looping through a dictionary of JSON data, for anything that has a single value as such:
var jsonData = ((TextBox)e.Item.FindControl("txtMessage")).Text;
var js = new JavaScriptSerializer();
var obj = js.Deserialize<dynamic>(jsonData);
foreach (KeyValuePair<string,object> item in obj)
{
var key = item.Key;
var value = item.Value;
if (key == "PercentageMatch")
{
((Label) e.Item.FindControl("lblMatchedPercent")).Text =
value.ToString();
}
}
I know need to add some additional code to read in the values of AKA's, which I know is more than up value, sometimes 10.
So, my code would look something similar to this:
var jsonData = ((TextBox)e.Item.FindControl("txtMessage")).Text;
var js = new JavaScriptSerializer();
var obj = js.Deserialize<dynamic>(jsonData);
foreach (KeyValuePair<string,object> item in obj)
{
var key = item.Key;
var value = item.Value;
if (key == "PercentageMatch")
{
((Label) e.Item.FindControl("lblMatchedPercent")).Text =
value.ToString();
}
if (key == "MatchedPerson")
{
foreach (KeyValuePair<string,object> aka in item)
{
}
}
}
but this isn't obviously correct.
I assume the value is supposed to be another dictionary, so you can do something like:
foreach(var aka in (IEnumerable<KeyValuePair<string, object>>)value)
{
}
also note that looping through the pairs of a dictionary and matching on key is inefficient, you could use TryGetValue instead:
object person;
if(obj.TryGetValue("MatchedPerson", out person))
{
foreach(var aka in (IEnumerable<KeyValuePair<string, object>>)person);
}

Categories