How to parse all usernames from Twitch chat API response

I’m working on a Perl script to fetch and parse usernames from a Twitch chat API endpoint. The API returns JSON data with different user categories, but my current code only captures the first username instead of collecting all of them.

I want to gather all usernames into an array and then filter out the category labels like “moderators”, “vips”, “broadcasters”, etc.

Here’s my current attempt:

use strict;
use warnings;

my @username_list = fetch_chatters();

sub fetch_chatters {
    my $api_url = "https://api.twitch.tv/helix/chat/chatters";
    my $response = get($api_url);
    my @parsed_data;
    my $counter = 0;

    while ($counter != 2){
        my $username = (join "", grep(/"\s*(.*?)\s*"/, $response[$counter])) =~ /"\s*(.*?)\s*"/;
        print $1;
        $counter++;
    }
    return @parsed_data;
}

print @username_list;

What’s the best way to extract all usernames from this JSON response and store them properly in an array?

Your main issue is you’re treating the JSON response like an array when it’s actually a string, plus you’re using regex instead of proper JSON parsing. The Twitch API sends back JSON data that needs to be decoded first. I ran into the same thing when I started with APIs in Perl. Use JSON::PP or JSON modules to parse the response properly. Something like my $data = decode_json($response); converts the JSON string into a Perl data structure. Once you’ve got the parsed data, just iterate through the chatters object and pull usernames from each category. The API usually returns categories like moderators, vips, viewers etc as separate arrays inside the chatters object. Also make sure you include proper headers in your HTTP request - especially the Client-ID header which Twitch requires. Without it you’ll get auth errors. Regex parsing JSON is unreliable and breaks with edge cases, so definitely switch to a proper JSON parser for better results.