Unable to perform for loop on json response object - c#

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

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.

C# Most elegant way to convert string array to dictionary with different keys

I have a collection of string arrays (result of splitting CSV to rows and then delimiting)
{31001, 2014-01-01, 24:00:00},{31001, 2014-01-02, 24:00:00},{31001, 2014-01-03, 24:00:00} ...
Now I need to convert it to list of dictionaries, where each dictionary element will have custom key depending on arrays element index. So I want to achieve something like this:
{
{"Index":"31001", "Date":"2014-01-01", "Time":"24:00:00"},
{"Index":"31001", "Date":"2014-01-02", "Time":"24:00:00"},
{"Index":"31001", "Date":"2014-01-03", "Time":"24:00:00"},
...
}
I can't use models for this
Assuming you will have duplicate keys you could use something like
List<KeyValuePair<string,Tuple<string,string>>
where the key is the Index and the rest of the data belongs in the Tuple (Date,Time,..etc).
If you will have more data you couls simply use a List<KeyValuePair<string,List<string>>>
You could do it with an anonymous object.
this way would result in objList having all the rows with the properties Index,Date and Time. whilst not using named classes.
(please note I'm still learning if I don't name things right)
List<Object> objList = new List<object>();
foreach(var line in lines)
{
var fields = line.Split(',');
objList.Add(new {
Index = fields[0],
Date = fields[1],
Time=fields[2]
});
}

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.

How to extract numbers from string array/dictionary using c#?

I have a string where its a string of a array of dictionaries.
An example of the format is:
[{"id":1,"items":[5,8]},{"id":2,"items":[6]},{"id":3,"items":[7]}]
(Note: all the above code is a string)
So here it is a string of an array of dictionaries that has two keys, the value of the first key is a number, and the value of the second key is a array of numbers.
Using c# (out of the box assemblies), how can I iterate through all the id values, and then all the item array values.
So I would expect like a double for loop. One to iterate through the id's and extract the number, and then for each iteration it would need to iterate through all the values of the items array.
Does anyone know how to go about parsing and extracting the numbers?
Thanks.
The output would be like ( for example )
1
5 8
2
6
3
7
EDIT:
I tried this:
string dataString = JSONValue.Text;
JavaScriptSerializer jss = new JavaScriptSerializer();
var json = new JavaScriptSerializer();
var data = json.Deserialize<List<Dictionary<string, Object>>>(dataString);
int sectionID;
List<int> itemIDS;
foreach (Dictionary<string, Object> dict in data)
{
sectionID = (int)dict["id"];
itemIDS = (List<int>)dict["items"];
ReportObject.log(sectionID.ToString());
foreach (int itemID in itemIDS)
{
ReportObject.log(itemID.ToString());
}
}
But am getting
(6/27/2013 12:02:04 AM) - Error Message: Unable to cast object of type 'System.Collections.ArrayList' to type 'System.Collections.Generic.List`1[System.Int32]'.
try this
using using System.Web.Script.Serialization;
var jsonStr = "[{\"id\":1,\"items\":[5,8]},{\"id\":2,\"items\":[6]},{\"id\":3,\"items\":[7]}]";
var json = new JavaScriptSerializer();
var data = json.Deserialize<List<dynamic>>(jsonStr);
this will generate a list of dynamic object with two properties id and items, then you can loop through that list and retrieve the info which you want.
The dynamic keyword only available from .net 4.0 or later. Otherwise you can use the following option.
create a class like this
public class Info{
public int Id { get; set; }
public int[] Items { get; set; }
}
and then var data = json.Deserialize<List<Info>>(jsonStr);
try getting the int value of string, if it's an array, get the object on the index specifically and try to the ToInt() or cast the string object to int. it can be done both ways.

Pass complex json via hidden variable and read in mvc 3 controller

I want to do the following.
Pass a complex json object in a hidden input variable
Get that hidden variable through the form collection object.
Convert that hidden text value to a dynamic object which I can loop through to
get the data from it
So I think the first two items above I can do.
$("#hiddenVariableID").val(JSON.stringify(data));
Have a parameter called FormCollection collection in the MVC controller.
Then get the value the following way String data =
collection.Get("hiddenVariableID");
?? Not sure how to do this.
The data I'm passing is an array of objects. The objects are never the same so that is why I need to convert the results in some type of dynamic object that I can loop through.
I can't do an ajax call to do this because I want to stream down the data passed in the hidden variable. So it has to be through a form submission.
Thank you,
-Tesh
You can at that point use some JSON parser to convert between the string and a JSON object you can access dynamically. There are many JSON parsers out there, the code below shows how it can be done with two of them: the JavaScriptSerializer (part of the .NET Framework), and the JSON.NET (a non-MS library, but which IMO is really good).
public static void Test()
{
string JSON = #"[
{'name':'Scooby Doo', 'age':10},
{'name':'Shaggy', 'age':18},
{'name':'Daphne', 'age':19},
{'name':'Fred', 'age':19},
{'name':'Velma', 'age':20}
]".Replace('\'', '\"');
Console.WriteLine("Using JavaScriptSerializer");
JavaScriptSerializer jss = new JavaScriptSerializer();
object[] o = jss.DeserializeObject(JSON) as object[];
foreach (Dictionary<string, object> person in o)
{
Console.WriteLine("{0} - {1}", person["name"], person["age"]);
}
Console.WriteLine();
Console.WriteLine("Using JSON.NET (Newtonsoft.Json) parser");
JArray ja = JArray.Parse(JSON);
foreach (var person in ja)
{
Console.WriteLine("{0} - {1}", person["name"].ToObject<string>(), person["age"].ToObject<int>());
}
}

Categories

Resources