Best way to take JSON and turn it into a useful object?
-
[C#]
I'm working through creating a bot to help maintain some community events on twitch tv
Criteria: I want to get a list of all users in the channel and parse them out into their proper groups so I don't have to manually maintain permissions outside of twitch.
This is probably extremely basic for anybody used to working with JSON - but I have very limited exposure to JSON, and usually only for objects I create for serialization/deserialization [thus can automagically handle it using libraries like fastJSON or newtonsoft.
A link is queried via webclient, and returns the following text:
{
"_links": {},
"chatter_count": 1969,
"chatters": {
"moderators": [
"bostv",
"botofsteel"
],
"staff": [],
"admins": [
"ravager"
],
"viewers": [
"0dawgy0",
"157yoshi157"
]
}
}I care about:
- chatter_count
- moderators
- staff
- admins
- viewers
I've got the key/value pairs as follows:
using (var w = new WebClient())
{
w.Proxy = null;
var jsonData = w.DownloadString(string.Format("http://tmi.twitch.tv/group/user/{0}/chatters", channel.Substring(1, channel.Length -1)));
var stream = JObject.Parse(jsonData);
foreach (var item in stream)
{
//Inner object data required here
Console.WriteLine(item.Key + "key, value: " + item.Value);
}
}
Any recommendations on parsing the inner elements without doing regex matching? foreach(json.data.key.innerkey/child....?)
Ultimately I'm going to take the results from the data and insert it into a database to track new users, returning users, etc. Basically I'm just trying to get to the inner most data, and tracking which category it's sourced out of.
[Edit] Looks like '.SelectToken("value"); is going to be my best bet?
-
I assume something similar is possible in C#
-
This is what I've ended up with so far, which should work, assuming the structure doesn't change (which is generally possible considering it's an unofficial endpoint for the twitch chat api)
using (var w = new WebClient()) { w.Proxy = null; var jsonData = w.DownloadString(string.Format("http://tmi.twitch.tv/group/user/{0}/chatters", channel.Substring(1, channel.Length -1))); var stream = JObject.Parse(jsonData.Replace(@"\r\n", "")); var chatLinks = stream.SelectToken(@"_links"); var chatCount = stream.SelectToken("chatter_count"); var getAdmins = stream.SelectToken("chatters").SelectToken("admins").Select(s => (string)s).ToList(); var getStaff = stream.SelectToken("chatters").SelectToken("staff").Select(s => (string)s).ToList(); var getModerators = stream.SelectToken("chatters").SelectToken("moderators").Select(s => (string)s).ToList(); var getViewers = stream.SelectToken("chatters").SelectToken("viewers").Select(s => (string)s).ToList(); }
Open to suggestions if anybody sees a better way to do it.
-
Why the substring-ing and the replace-ing?
-
Reusing a channel variable defined on connect, which is #channelname
the data comes back with \r\n's in it, that was just a relic from my debugging which can be removed
I think.
-
This is a less fragile way to do it: http://msdn.microsoft.com/en-us/library/bb412179(v=vs.110).aspx
-
Just FYI, to post code, indent by 4 spaces, or use a fenced code block (3 backticks on the first and last lines).
-
In similar situations, I would create a NET object structure matching the javascript one, and then use Json.NET to deserialize json into CLR. Then you can do whatever you want using normal c# methods.
public class Data { public int chatter_count { get; set; } public Chatters chatters { get; set; } public class Chatters { public List<string> moderators { get; set; } public List<string> staff { get; set; } public List<string> viewers { get; set; } public List<string> admins { get; set; } } } // ... var data = JsonConvert.DeserializeObject<Data>(json); Console.WriteLine(data.chatter_count); Console.WriteLine(data.chatters.moderators[0]); //...
-
Not the < code > html tags?
Because, why?
-
I think this is actually what I'm looking for - I thought about it last night, but couldn't reconcile to this object (key piece I was missing was the embedded public class chatters)
So +1 to you sir, and will update my implementation.
-
Not the < code > html tags?
Because, why?
have you() {
tried that yet?
}If you had, you'd know why…
-
Sorry, let me clarify my whining.
Why should I have to use three ` instead of something explicitly called < code> - Why the fuck is three ` more discoverable than the code tag?
Why the fuck do I have to manually escape my `?
-
Because <code> is an inline element
and <pre> is a block element.
-
and ctrl+f is a browser feature.
-
I see your ctrl + f and raise you "scrollbar", which is an operating system feature
-
"scrollbar", which is an operating system feature
Graphics toolkit, not OS.
Filed under: technically correct, the best kind of correct!
-
Yeah, it's also broken in Google Docs. Can you go file a bug there, too? ;)
Back on topic,
<pre>
is a block level element, whereas<code>
is inline.Which means
use pre when you have multiple lines
and
use code when it's a single line mixed with other content
like soIt's just how HTML works.
-
I would if i used google docs, but i don't. But you can control your own software.
-
Again, just because it's broken in
<other system>
does not give you justification to leave it broken in your system.Filed under:
<code style="display:block">Hey look, ma</code>
-
"Just because it's an innate part of HTML doesn't mean you have to be affected by it when you use HTML."
Filed under: wait
-
That's what's so cool about HTML, you can redefine things on the fly and have all kinds of neat altered behaviour!
It's like the people who do shit like this in the CSS:
b, strong { font-weight: normal; font-style: italic; }
It's a useful tool, at times, but like anything else that's prone to the Dark Side of the Source, one must not give into temptation to REDECLARE ALL THE THINGS!
-
I see it as more method overloading. Inline code doesn't make much sense in the context of a forum.
-
Inline code doesn't make much sense in the context of a forum.
I wonder why inline
<code>
gets used so much, then.
-
Examples.
-
How about this post:
-
Just do the standard four spaces like stack overflow.
-
Yeah, it's also broken in Google Docs. Can you go file a bug there, too?
Sorry?
Find works in google docs. It's overridden, but it works in exactly the way plain-jane, browser-level find works.
Also, the scrollbar works in Google docs. Just uploaded a 1200-page document to test it. It looks marginally different, so they're obviously overriding the browser's implementation, but it works just like the original.
-
You taking up coding horrors self quoting? Imo code tag is for code, and you don't inline code.
-
You could always use dynamic to make life a bit easier:
dynamic json = JsonConvert.DeserializeObject(jsonData);
you can then use:
json.chatters
json.chatters.moderators - this would be an array you could foreach on, etc
json.chatter_count
etc in your code without having to manually create each object.
-
Why the fuck is three ` more discoverable than the code tag?
Because it's is the FAQs?
-
Yeah, it's also broken in Google Docs.
This sounds familiar:
I guess google docs is doing it wrong then.
To which you were told:
[Y]ou keep pointing to big companies like Google when someone tells you you're doing something stupid, and saying "but they're doing it too!" Did you ever try that argument with your parents? Remember them saying "If your friends jumped off a cliff, would you do it, too?" In short, just because Google, or Adobe, or Microsoft does, doesn't mean it's right.
And this was added:
Examples of Doing It Wrong can be found in all of those, and even if something one of them does is right for a particular situation, it doesn't necessarily meant it's right for a different situation. Google Docs is not a discussion forum, so using it as an example of how forum software should behave is odd.
In short, your argument about Ctrl+F and Google Docs has been shot down already. Give it up. It does not apply here.
-
If your friends all jumped off a bridge at once, would you?
What's more likely:
- The bridge is on fire
- There is a car coming in the pedestrian lane
- You are at a bungee jumping convention
- All your friends simultaneously decided to commit suicide
-
You forgot:
- They're all drunk and thought it was a good idea
-
If your friends all jumped off a bridge at once, would you?
What's more likely:
- The bridge is on fire
- There is a car coming in the pedestrian lane
- You are at a bungee jumping convention
- All your friends simultaneously decided to commit suicide
You forgot:
- They're all drunk and thought it was a good idea
I was just referencing the stereotypical question that parents give when a kid says "But all my friends are doing it." If you want a "What's more likely" answer, go ask your parents.
-
We know
The whole 'just because other company does it' thing does not justify insane coding. If that were true, TDWTF wouldn't exist because all previous bad WTFs would set a precedent for legitimising future WTFs.
-
I'd like to come live in your fantasy world.
-
Sadly that fantasy world really is a fantasy, because past WTFs do not legitimise future WTFs because it's still jam-packed full of WTF.
-
You can't fight
City HallPHB.
-
This is something that @Nagesh is also doing.
-
This is something that @Nagesh is also doing.
Do you like talking about yourself in third person? Are you offering to be the next mention bomb victim? Cause that kind of takes the fun out of it.
-
Do you like talking about yourself in third person? Are you offering to be the next mention bomb victim? Cause that kind of takes the fun out of it.
Gabbar ke taap se tumhe ek hi aadmi bacha sakta hai, ek hi aadmi, khud Gabbar.
-
-
Being a father of three small children (5 and under), "Gabba" makes me think of Yo Gabba Gabba.
I Like To Dance - Yo Gabba Gabba! – 02:18
— Yo Gabba Gabba! - WildBrain
-
Gabbar is not same as Gabba. 3 children? are you also married happily?
-
are you also married happily?
With three children? I don't think he has the time to even think about if he's happy or not.
-
I don't think he has the time to even think about if he's happy or not.
Sure I do, after they go to bed. Remember, they're young. They're all asleep by 8pm, so my wife and I have plenty of time to be "happy."
-
Sure I do, after they go to bed. Remember, they're young. They're all asleep by 8pm, so my wife and I have plenty of time to be "happy."
I misread your post as 3 and under. In that case, yeah, my buttumption was wrong.
-
They're all asleep by 8pm
In my country, parents are not home before 8:30 PM, so children go to bed only by 10:00 - 11:00, sometime even as late as midnight. Transport, traffic and work condition have casted this misery on us.
-
Bummer. I rarely get home after 6:00 PM, and I'm usually home by 1700.
Filed Under: Yes, I did that on purpose
-