how to iterate through json array - c#

How do we iterate through the Map array?
My payload looks like this:
{
"Record": "...bunch of hl7 data...",
"Map": [{ "DG1.2": "PatientDiag1" }, { "DG1.3": "PatientDiag2" }]
}
How do we iterate and parse the values of the Map array?
I've tried the following:
var blobObject = JObject.Parse(blob);
var map = blobObject["Map"]; //it's a JToken at this point
//now let's parse each key/value pair in the map:
foreach (var field in map)
{
var key = field.ToString();
var value = field[0].Value
}

"Map" is an array of JSON objects, so first you need to loop through the array, then you can loop through the key/value pairs of each object:
var blobObject = JObject.Parse(blob);
var map = blobObject["Map"]; //it's a JToken at this point
//now let's parse each key/value pair in the map:
foreach (var item in map.Cast<JObject>()) // Map is an array of objects so loop through the array, then loop through the key/value pairs of each object
{
foreach (var pair in item)
{
var key = pair.Key;
var value = pair.Value;
}
}
Or if you prefer to flatten the array with LINQ's SelectMany():
foreach (var pair in map.SelectMany(o => (IDictionary<string, JToken>)o))
{
var key = pair.Key;
var value = pair.Value;
}
Notes:
From the JSON spec
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
A JSON array is mapped to a JArray while a JSON object is mapped to a JObject.
How do we ... parse the values of the Map array? You don't need to parse the values of the Map array, they are already fully parsed. You just need to query them with LINQ to JSON.
Demo fiddle here.

var blobObject = JObject.Parse(blob);
var map = blobObject["Map"];
var values = map.Values().OfType<JProperty>();
foreach (JProperty prop in values)
{
Console.WriteLine(prop.Name); // property name
Console.WriteLine(prop.Value);// property value
}
Get all the values from Map key as JProperty, then loop through each property and you can access the property name using prop.Name and the value using prop.Value.

Related

Json.Net Key/Value Pair to dictonary object

I am trying to extract the below key-value pair in JSON to dictonary.
var str = #"
{
""tables"": {
""category"": ""Category"",
""subcategory"": ""SubCategory"",
""tfs"": ""tfs"",
""tickets"": ""snowtickets"",
""ticketcategoryauto"": ""TicketCategoryAuto"",
""ticketcategoryuserselected"": ""TicketCategoryManual""
}
}
";
var jo = JObject.Parse(str);
var x = from c in jo["tables"] select c;
I want the "tables" node of this Json into a dictionary object. so if I say x["category"] should get back "Category" similarly for other keys. How can I do that.
tables is a dictionary type object so you need to return it as a type of Dictionary.
var jo = JObject.Parse(str);
Dictionary<string, string> values = jo["tables"].ToObject<Dictionary<string,string>>();

Unable to perform for loop on json response object

I have dictionary of categories & their types in .cs file such as
Dictionary<string, List<string>> jsonDic
I have converted it into the json object string using following logic:
JavaScriptSerializer jss = new JavaScriptSerializer();
string barJson = jss.Serialize(jsonDic);
string js = "TypesArray(" + barJson + ")";
ScriptManager.RegisterStartupScript(this, this.GetType(), "Startup1", js, true);
Now, in .js file I am getting following response
As we can see result is not in the form of array I am not able to index tpoints since it is not an array. What should I do? I want to index categories also types assosiated with each category..
You can access any of the attributes by name
tpoints["Foods"]
and that returns you an array of strings, in the foods case
[Restaurant, Cafe, Bakery]
If you want to iterate,
for (var property in tpoints ) {
if (tpoints.hasOwnProperty(property)) {
// do stuff
}
}
I think you are getting very confused with the kind of data structure you're working with. First, you're question title is false...
Unable to perform for loop on json response object
because you are indeed looping through the json objects. When you serialize the object below...
Dictionary<string, List<string>> jsonDic;
the serializer is actually mapping each KeyValuePair object inside the dictionary to a json array item, that is tPoint. So, to iterate through this array all you have to do is the following...
for (var tpoint in tpoints ) {
tpoint.Foods; //get food array
tpoint.Foods[0]; //get the first food item
}
and so on, you could even add a nested for loop to iterate through each inner array as below...
for (var tpoint in tpoints ) {
for(var i = 0; i < tpoint.Foods.length;i++){
console.log(tpoint.Foods[i]);
}
}
this will iterate through all food items in every tpoints

How to get keys from the List of Dictionary

I have jsondata which is coming in form of List of Dictionary ..I need to extrct Key and value from each iteration
This is what I have Tried ..
var json = new WebClient().DownloadString(url);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string,object>> json = serializer.Deserialize<List<Dictionary<string,object>>>(json);
foreach (Dictionary<string, object> record in jsonList )
{
var imei = record.Keys;
}
The above Code return another array of Keys in which I have to select First Element .
This Happens in every Iteration ...I need single Key.Not the Array of Keys
Try this
var keys = json.Select(d => d.Keys.First()).ToList();
will return first keys from each dictionary

How to get value from dictionary without knowing key?

I want to get value from dictionary but i don't know key(Because dynamic generate dictionary from database) how can i get dictionary value.
If you some idea share me ...
For Example my database string value like
string jsonString = " "FB": "[{\"title\":\"sheet1\",\"rows\":[{\"height\":\"undefined\",\"columns\":[{\"value\":\"Cover Group \"},{\"value\":\"Sample Variable\"},{\"value\":\"Coverpoint Name\"},{\"value\":\"Crossed cover points\"},{\"value\":\"Coverpoint Comment\"},{\"value\":\"Bin Type\"},{\"value\":\"Bin Id\"},{\"value\":\"Sample Value\"},{\"value\":\"Expected Bin Count\"},{\"value\":\"Set Max Bin\"},{\"value\":\"Not Used\"}]},{\"height\":\"undefined\",\"columns\":[{\"value\":\"allCg,allSi\"},{\"value\":\"exSingle\"},{\"value\":\"exSingle\"},{},{\"value\":\"Example for single bin\"},{\"value\":\"single\"},{\"value\":\"valZero\"},{\"value\":\"1'b0\"},{\"formula\":\"1\",\"value\":1},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{},{},{},{},{\"value\":\"single\"},{\"value\":\"valOne\"},{\"value\":\"1'b1\"},{\"formula\":\"1\",\"value\":1},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{\"value\":\"ex1Bus[3:0]\"},{\"value\":\"exMulti\"},{},{\"value\":\"Example for multibin\"},{\"value\":\"multi\"},{},{\"value\":\"[0:15]\"},{\"formula\":\"16\",\"value\":16},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{},{\"value\":\"exCross\"},{\"value\":\"exSingle,exMulti\"},{\"value\":\"Example for cross\"},{\"value\":\"Implicit\"},{},{},{\"formula\":\"32\",\"value\":32},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{\"value\":\"ex2Bus[15:0]\"},{\"value\":\"exWildcard\"},{},{\"value\":\"example for wildcard\"},{\"value\":\"wildcard\"},{\"value\":\"ex_wildcard\"},{\"value\":\"16'bxxxxxxxxxxxxxx1\"},{\"formula\":\"1\",\"value\":1},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{\"value\":\"ex3Bus[4:0]\"},{\"value\":\"exImplicit\"},{},{\"value\":\"example for implicit & set max bin\"},{\"value\":\"Implicit\"},{},{},{\"formula\":\"8\",\"value\":8},{\"formula\":\"8\",\"value\":8},{}]},{\"height\":\"undefined\",\"columns\":[{},{\"value\":\"ex4Bus[3:0]\"},{\"value\":\"ex4Bus\"},{},{\"value\":\"setup for ignore example\"},{\"value\":\"multi\"},{},{\"value\":\"[0:15]\"},{\"formula\":\"16\",\"value\":16},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{},{\"value\":\"exIgnore\"},{\"value\":\"exSingle,ex4Bus\"},{\"value\":\"example for ignore\"},{\"value\":\"ignore\"},{},{\"value\":\"ex4Bus([12:15])\"},{\"formula\":\"24\",\"value\":24},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{\"value\":\"ex5Bus[3:0]\"},{\"value\":\"exIllegal\"},{},{\"value\":\"example for illegal\"},{\"value\":\"illegal\"},{},{\"value\":\"[12:15]\"},{\"formula\":\"16\",\"value\":16},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{},{},{},{},{},{},{},{},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{},{},{},{},{},{},{},{},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{},{},{},{},{},{},{},{},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{},{},{},{},{},{},{},{},{},{}]},{\"height\":\"undefined\",\"columns\":[{},{},{},{},{},{},{},{},{},{},{}]}],\"metadata\":{\"widths\":[\"200\",\"200\",\"200\",\"200\",\"200\",\"200\",\"200\",\"200\",\"200\",\"200\",\"200\"],\"frozenAt\":{\"row\":0,\"col\":0}}}]""
FB is dynamic key and after it's value title all value i need
If you don't have the key, but have the value and trying to get hold of the key, you can do this:
Dictionary<string, string> testData = new Dictionary<string, string>();
testData.Add("name", "Latheesan");
testData.Add("age", "26");
KeyValuePair<string, string> searchResult
= testData.FirstOrDefault(s => s.Value == "Latheesan");
string key = searchResult.Key; // returns "name" here
To get a sequence of all the Key/Value pairs where the value matches a target:
var dict = new Dictionary<string, int>
{
{"One", 1},
{"Two", 2},
{"Another One", 1},
{"Three", 3},
{"Yet Another One", 1}
};
int target = 1; // For example.
var matches = dict.Where(item => item.Value == target);
foreach (var kvp in matches)
Console.WriteLine("Key = " + kvp.Key);
The sample data you posted isn't a flat key-value dictionary. It contains embedded dictionaries - the base dictionary contains a title and a rows, which in turn consists of height and columns and so on, and at some point are key-value pairs who keys are, confusingly, named 'value'. Are you asking how to parse this data structure to get all the values whose key is value?
What you first need to do, since this appears to be a JSON-formatted entry, is parse the JSON into a .NET data structure, using libraries like JSON.NET or System.Web.Helpers.Json. These libraries will convert the JSON string into a hierarchy of dictionaries, all of them implementing IEnumerable, so you can iterate over it, more or less like this (this is not compilable code, just a demonstration!):
public void Main()
{
var jsonObject = Json.Decode(FB); // FB is your JSON string.
var values = new List<string>();
FindValues(jsonObject);
}
public void FindValues(jsonObject, values)
{
foreach (var child in jsonObject)
{
if (child.key == 'value')
{
values.Add(child.value);
}
// Recursively call FindValues on child objects.
FindValues(child, values);
}
}
This C#-ish pseudo-code shows you how to go over a dictionary, then optionally drill down deeper into internal dictionaries.
This code use for get value from dictionary value without knowing key and value..
var json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonString );
var javSer = new JavaScriptSerializer();
var dfi = javSer.Deserialize<Dictionary<string, string>>(json);
string dataString= dfi.Values.First();
How can you possibly know which value you need if you don't have the key?
A Dictionary in .NET does contain a Keys and Values collection, so if you are only interested in the values, you can use that.

Getting the name / key of a JToken with JSON.net

I have some JSON that looks like this
[
{
"MobileSiteContent": {
"Culture": "en_au",
"Key": [
"NameOfKey1"
]
}
},
{
"PageContent": {
"Culture": "en_au",
"Page": [
"about-us/"
]
}
}
]
I parse this as a JArray:
var array = JArray.Parse(json);
Then, I loop over the array:
foreach (var content in array)
{
}
content is a JToken
How can I retrieve the "name" or "key" of each item?
For example, "MobileSiteContent" or "PageContent"
JToken is the base class for JObject, JArray, JProperty, JValue, etc. You can use the Children<T>() method to get a filtered list of a JToken's children that are of a certain type, for example JObject. Each JObject has a collection of JProperty objects, which can be accessed via the Properties() method. For each JProperty, you can get its Name. (Of course you can also get the Value if desired, which is another JToken.)
Putting it all together we have:
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
Console.WriteLine(prop.Name);
}
}
Output:
MobileSiteContent
PageContent
JObject obj = JObject.Parse(json);
var attributes = obj["parent"]["child"]...["your desired element"];
foreach (JProperty attributeProperty in attributes)
{
var attribute = attributes[attributeProperty.Name];
var my_data = attribute["your desired element"];
}
The default iterator for the JObject is as a dictionary iterating over key/value pairs.
JObject obj = JObject.Parse(response);
foreach (var pair in obj) {
Console.WriteLine (pair.Key);
}
Using Linq we can write something like:
JArray array = JArray.Parse(json);
foreach (JObject content in array.Children<JObject>())
{
List<string> keys = content.Properties().Select(p => p.Name).ToList();
}
If the JToken key name is unknown, and you only need the key's Value regardless of name, simply use the JToken.Values() method.
The below sample assumes the JToken value is a primitive type - first value found is extracted.
Solution can be extended to support Array values.
JToken fooToken = sourceData.
int someNum = fooToken .Values<int?>().First() ?? 0;
int someString = fooToken .Values<string>().First();
The simplest way is to look at the path of each item in the JSON object.
For Each token As JToken In json
Dim key= token.Path.Split(".").Last
Next

Categories

Resources