Home > OS >  How do I take a JSON string and select a random entry and get the variables from that entry
How do I take a JSON string and select a random entry and get the variables from that entry

Time:07-05

I have the following json..

{
    "Followers": [{
        "ID": 0,
        "Username": "nutty",
        "Game": "Just Chatting",
        "Viewers": 200,
        "Image": "https://static-cdn.jtvnw.net/previews-ttv/live_user_nutty-1920x1080.jpg"
    }, {
        "ID": 1,
        "Username": "CloneKorp",
        "Game": "Software and Game Development",
        "Viewers": 31,
        "Image": "https://static-cdn.jtvnw.net/previews-ttv/live_user_clonekorp-1920x1080.jpg"
    }, {
        "ID": 2,
        "Username": "kingswarrior9953",
        "Game": "Art",
        "Viewers": 1,
        "Image": "https://static-cdn.jtvnw.net/previews-ttv/live_user_kingswarrior9953-1920x1080.jpg"
    }]
}

I'd like to do something like..

JObject data = JObject.Parse(json);
int SelectedViewers = data["Followers"][1]["Viewers"];

Where it would grab the second entry (the ID of 1 entry) and set the variable of "Viewers" to 31. The number would be a random number based on the count of all the entries, but I'm not to that point yet.

However, this doesn't seem to work. Any ideas on what is broken here?

CodePudding user response:

You are missing casting here:

int SelectedViewers = Int32.Parse((string)data["Followers"][1]["Viewers"]);

The above should work.

CodePudding user response:

try this

   using Newtonsoft.Json;
   using Newtonsoft.Json.Linq;

    var followers = (JArray)JObject.Parse(json)["Followers"];
    var id=1;
    
    int selectedViewers = followers.Where(f=> (int)f["ID"]==id)
                                   .Select(f => (int) f["Viewers"])
                                   .FirstOrDefault();  //31
  • Related