How do I enumerate through a JObject?
If you look at the documentation for JObject
, you will see that it implements IEnumerable<KeyValuePair<string, JToken>>
. So, you can iterate over it simply using a foreach
:
foreach (var x in obj)
{
string name = x.Key;
JToken value = x.Value;
…
}
How to iterate through JProperties of JObject key with JSON.Net
All JToken
objects contain properties that allow you to operate on any object as if it were any of the valid json types.
In json.net in particular, the children of objects are JProperty
. So just get the children of the object.
var query =
from x in json["Developments"].Children<JProperty>()
select x.Name;
On the other hand, if it is already typed as a JObject
, you could access the properties directly.
var query =
from x in ((JObject)json["Developments"]).Properties()
select x.Name;
How do I enumerate nested JObject using JSON.net?
If you want to iterate all nested objects as well you can do something like this:
var p = JObject.Parse(...);
foreach (var a in p.DescendantsAndSelf())
{
if (a is JObject obj)
foreach (var prop in obj.Properties())
if (!(prop.Value is JObject) && !(prop.Value is JArray))
Console.WriteLine(" {0}: {1}", prop.Name, prop.Value);
}
JObject structure - How to iterate?
The first thing to do is understand your structure. It's somewhat odd, because value
is actually an array, containing a single object. You should work out what you would want to do if you ever had multiple objects there.
Here's an example which dumps the values from each item of the array. This works after changing the {{ ... }}
in your JSON to { ... }
.
using System;
using System.IO;
using Newtonsoft.Json.Linq;
public class Test
{
static void Main()
{
var json = File.ReadAllText("test.json");
var obj = JObject.Parse(json);
var valueArray = (JArray) obj["value"];
// Note: if the array contains non-objects,
// this will fail
foreach (JObject value in valueArray)
{
Console.WriteLine("Values:");
foreach (var property in value.Properties())
{
Console.WriteLine(" {0}: {1}", property.Name, property.Value);
}
}
}
}
Output:
Values:
uploadid: valuevaluevalue
parentid: othervalue
id: idvalue
filename: account.xml
displayname: account.xml
size: 116
md5:
To get just the ID, you could use value["id"]
.
Looping through JObject c#
Try like this:
JObject jsonObject = JObject.Parse(myJson);
foreach (JToken fundingSource in jsonObject.SelectToken("_embedded.funding-sources"))
{
bool removed = (bool)fundingSource["removed"];
if (!removed)
{
string href = (string)fundingSource.SelectToken("_links.self.href");
Console.WriteLine(href);
}
}
Fiddle: https://dotnetfiddle.net/Jhw8w6
Alternatively you can use LINQ like this:
JObject jsonObject = JObject.Parse(myJson);
List<string> links = jsonObject.SelectToken("_embedded.funding-sources")
.Where(fundingSource => !(bool)fundingSource["removed"])
.Select(fundingSource => (string)fundingSource.SelectToken("_links.self.href"))
.ToList();
Console.WriteLine(string.Join(Environment.NewLine, links));
Fiddle: https://dotnetfiddle.net/gnyGgk
Looping through multiple JObject levels and gathering information as a string
You have some errors in your JSON. Check it with jsonlint.com. I think it should look something like this:
{
"success": true,
"rgInventory": {
"Blah other stuff": ""
},
"rgDescriptions": {
"637390365_0": {
"appid": "753",
"background_color": "",
"type": "0RBITALIS Trading Card"
},
"175240190_0": {
"appid": "753",
"background_color": "",
"type": "Awesomenauts Trading Card"
},
"195930139_0": {
"appid": "753",
"background_color": "",
"type": "CONSORTIUM Emoticon"
}
}
}
You can use the JProperty, JToken and the SelectToken Method to get the type:
var json = new WebClient().DownloadString("http://steamcommunity.com/id/tryhardhusky/inventory/json/753/6");
JObject jo = JObject.Parse(json);
foreach (JProperty x in jo.SelectToken("rgDescriptions"))
{
JToken type = x.Value.SelectToken("type");
string typeStr = type.ToString().ToLower();
if (typeStr.Contains("background"))
{
Console.WriteLine("Contains 'background'");
}
if (typeStr.Contains("emoticon"))
{
Console.WriteLine("Contains 'emoticon'");
}
if (typeStr.Contains("trading card"))
{
Console.WriteLine("Contains 'trading card'");
}
}
How do I loop over this JObject?
Here is an example of how to loop through your JSON:
JObject obj = JObject.Parse(json);
JArray segmentGroups = (JArray)obj.Properties().FirstOrDefault()?.Value;
if (segmentGroups != null)
{
foreach (JObject group in segmentGroups.Children<JObject>())
{
string name = (string)group["name"];
string desc = (string)group["description"];
string[] segments = group["segments"]?.ToObject<string[]>();
Console.WriteLine("name: " + (name ?? "(null)"));
Console.WriteLine("description: " + (desc ?? "(null)"));
Console.WriteLine("segments: " + (segments != null ? "\n " + string.Join("\n ", segments) : "(null)"));
Console.WriteLine();
}
}
Fiddle: https://dotnetfiddle.net/kOJzaZ
Looping through JObject nested array
You can achieve it using the following code
var jsonObject = JObject.Parse(json);
foreach (var entry in jsonObject["entries"])
{
foreach (var run in entry["runs"])
{
string returnable = (string)run["id"];
Console.WriteLine(returnable);
}
}
You would like to see
169
170
They are an id
values from runs
array, therefore you should enumerate them in the inner loop. You've also missed a comma after "name": "section 1"
Related Topics
How to Embed an Application Manifest into an Application Using VS2008
Why Datetime.Addhours Doesn't Seem to Work
Wrapping Stopwatch Timing with a Delegate or Lambda
Mongodb Gridfs with C#, How to Store Files Such as Images
Importing Nested Namespaces Automatically in C#
For Loop Not Returning Expected Value - C# - Blazor
For I = 0, Why Is (I += I++) Equal to 0
Entity Framework 6: Audit/Track Changes
Force JSON.Net to Include Milliseconds When Serializing Datetime (Even If Ms Component Is Zero)
Create a Coroutine to Fade Out Different Types of Object
Why Are Subjects Not Recommended in .Net Reactive Extensions
How to Keep a .Net Console App Running
How to Pinvoke to Getwindowlongptr and Setwindowlongptr on 32-Bit Platforms
Trying to Insert Datetime.Now into Date/Time Field Gives "Data Type Mismatch" Error
Setting Unique Constraint with Fluent API
Passing an Enum Value as Command Parameter from Xaml
Shortcut for "Null If Object Is Null, or Object.Member If Object Is Not Null"