Home > Software engineering >  How to iterate over dynamic objects
How to iterate over dynamic objects

Time:04-15

I'm using newtonsoft json To read a file with tests and i put it into a dynamic object. this works nice for the static config part However the tests part consists of tests, who's syntax is less static. Some items can be different.

So my json file test.json looks alike: (shortened)

{"config":{"user":"Nico",userID:"54"},
 "tests":[ {"ask":"test1","handshake":false},
           {"ask":"test2","handshake":false},
           {"ask":"test3","handshake":true,"verify":"true"}
           {"ask":"test4","handshake":false},
           {"send":"result4"} 
           {"ask":"test7","repeat":30,"delay":120,"brakefail":false} ] 
 }

I converted it to a dynamic object, and reading out the config part works nicely:

dynamic testfile = JObject.Parse(File.ReadAllText( "c:\\test.json"));
Console.WriteLine (testfile.config.user);
Console.Writeline (testfile.config.userID);  //this works

But now I wonder what is the syntax to iterate the tests ?
As they can differ slightly in options, how to parse them. (the tests change high frequently).

CodePudding user response:

tests is an JArray. you can iterate the test with a simple foreach

foreach(JObject test in testfile.tests)
{
    if(test.ContainsKey("ask"))
        Console.WriteLine(test.GetValue("ask"));
}

but you need to verify that there is a variable like "ask"

CodePudding user response:

JObject.Parse() returns a JObject type that can be indexed with any valid string key like 'tests' in your case. Then you can use the returned value, which is of type JToken, to enumerate the items.

Here is an example:

var jObject = JObject.Parse("{\"tests\":[{\"name\":\"Hana\"},{\"name\":\"Nita\"}]}");
foreach (var item in jObject["tests"])
            Console.WriteLine(item["name"]);
  • Related