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
Related
JSON data:
{
"return": {
"output01": "Test request success!!",
"output02": "test request"
}
}
C# code:
JObject obj = JObject.Parse(jsonString);
JToken jToken = obj["return"];
foreach (JToken item in jToken)
{
string output1_param = item["output01"].ToString();
string output2_param = item["output02"].ToString();
}
Think of a repeat case.
System.InvalidOperationException: 'Cannot access child value on
Newtonsoft.Json.Linq.JProperty.'
What's wrong?
item is a JProperty, so it does not support indexer by object key (for example string one). You need either strip foreach:
JToken jToken = obj["return"];
string output1_param = jToken["output01"].ToString();
string output2_param = jToken["output02"].ToString();
Or work with Values of item, for example via First:
foreach (JToken item in jToken)
{
Console.WriteLine(item.First.ToString());
}
Also in this case casting to JProperty in foreach is also an option:
foreach (JProperty item in jToken)
{
Console.WriteLine($"{item.Name} - {item.Value}");
}
as you can see in This Link, indexer of JToken does not implemented and your code tries to using indexer of JToken.
When you call GetEnumerator of jToken, in this sample you will get just single element which is JProperty, so calling indexer of JProperty(by using string key) which implemented JToken will try using this indexer and throws exception.
what happens if you call using this way:
jToken["output01"].ToString();
in this pattern you are using indexer of JObject, which iterates over ChildrenTokens of JObject and give you values.
as Guru said you must read value using value field or use First element.
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.
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
How to iterate through pure JSON Array like the following, in C# Newtonsoft?
[
78293270,
847744,
32816430
]
or,
["aa", "bb", "cc"]
All the existing answers that I found on SO are in KeyValuePair format, not this pure JSON Array format. Thx.
JArray array = JsonConvert.DeserializeObject<JArray>(json);
foreach(JObject item in array)
{
// now what?
}
Parse the string using static Parse method of JArray. This method returns a JArray from a string that contains JSON. Please read it about here.
var jArray = JArray.Parse(arrStr);
foreach (var obj in jArray)
{
Console.WriteLine(obj);
}
A simple program for your inputs which you can run to validate at dotnetfiddle.
using System;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
var arrStr = "[78293270, 847744, 32816430]";
var jArray = JArray.Parse(arrStr);
foreach (var obj in jArray)
{
Console.WriteLine(obj);
}
var aStr = "[\"aa\", \"bb\", \"cc\"]";
var jArray1 = JArray.Parse(aStr);
foreach (var obj in jArray1)
{
Console.WriteLine(obj);
}
}
}
The output of above code is
78293270
847744
32816430
aa
bb
cc
Dotnet Fiddle program
Do you mean "how to get values from iterated JObject?
foreach(var item in array) // var is JToken, can be cast to JObject
{
int number = item.Value<int>();
Console.WriteLine(number);
}
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>>();