How to get keys from the List of Dictionary - c#

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

Related

how to iterate through json array

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.

How to iterate through a dictionary to get and pass key name to string

I'd like to iterate through a C# dictionary storing nested JSON to retrieve and pass the dictionary key name to a string, in the form of "key1:key1-1:key1-1-1".
After that, a new dictionary is created to use the specially arranged string as its keys.
Finally, desiredDictionary["key:key:key"] = originalDictionary["key"]["key"]["key"].
Please make the answer specific, my apology that I'm new to C# IEnumerable class and JSON.
I've stored the JSON data into a dictionary, the sample JSON is given below.
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
......
string jsonText = File.ReadAllText(myJsonPath);
var jss = new JavaScriptSerializer();
//this is the dictionary storing JSON
var dictJSON = jss.Deserialize<Dictionary<string, dynamic>>(jsonText);
//this is the dictionary with keys of specially arranged string
var desiredDict = new Dictionary<string, string>();
......
......
//Here is a sample JSON
{
"One": "Hey",
"Two": {
"Two": "HeyHey"
}
"Three": {
"Three": {
"Three": "HeyHeyHey"
}
}
}
I need help with the process for dictionary key name retrieval, string completion, and new dictionary value passing.
According to the given JSON, desiredDict["Three:Three:Three"] = dictJSON["Three"]["Three"]["Three"] = "HeyHeyHey",
The solution is expected to apply on any similar JSON.
You can use a recursive method to take a JObject and produce a flattened dictionary from it like so:
private static IDictionary<string, string> FlattenJObjectToDictionary(JObject obj)
{
// obtain a key/value enumerable and convert it to a dictionary
return NestedJObjectToFlatEnumerable(obj, null).ToDictionary(kv => kv.Key, kv => kv.Value);
}
private static IEnumerable<KeyValuePair<string, string>> NestedJObjectToFlatEnumerable(JObject data, string path = null)
{
// path will be null or a value like Three:Three: (where Three:Three is the parent chain)
// go through each property in the json object
foreach (var kv in data.Properties())
{
// if the value is another jobject, we'll recursively call this method
if (kv.Value is JObject)
{
var childDict = (JObject)kv.Value;
// build the child path based on the root path and the property name
string childPath = path != null ? string.Format("{0}{1}:", path, kv.Name) : string.Format("{0}:", kv.Name);
// get each result from our recursive call and return it to the caller
foreach (var resultVal in NestedJObjectToFlatEnumerable(childDict, childPath))
{
yield return resultVal;
}
}
else if (kv.Value is JArray)
{
throw new NotImplementedException("Encountered unexpected JArray");
}
else
{
// this kind of assumes that all values will be convertible to string, so you might need to add handling for other value types
yield return new KeyValuePair<string, string>(string.Format("{0}{1}", path, kv.Name), Convert.ToString(kv.Value));
}
}
}
Usage:
var json = "{\"One\":\"Hey\",\"Two\":{\"Two\":\"HeyHey\" },\"Three\":{\"Three\":{\"Three\":\"HeyHeyHey\"}}}";
var jObj = JsonConvert.DeserializeObject<JObject>(json);
var flattened = FlattenJObjectToDictionary(jObj);
It takes advantage of yield return to return the results of the recursive call as a single IEnumerable<KeyValuePair<string, string>> and then returns that as a flat dictionary.
Caveats:
Arrays in JSON will throw an exception (see else if (kv.Value is JArray))
The else part for handling the actual values assumes that all values are convertible to string using Convert.ToString(kv.Value). If this is not the case, you will have to code for extra scenarios.
Try it online

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 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.

Categories

Resources