Search code examples
jsondiscord.jsnode-fetch

Getting the error "SyntaxError: Unexpected token u in JSON at position 0" when fetching random posts from a subreddit


When I try to fetch a post from https://www.reddit.com/r/hoodironycentral/random/.json it returns me undefined while JSON.parse is running.

Here is my code:

import { EmbedBuilder, PermissionsBitField, SlashCommandBuilder } from "discord.js";
import fetch from "node-fetch";

export default {
    data: new SlashCommandBuilder()
      .setName("hoodclassic")
      .setDescription("haha so funny"),
      run: async (client, interaction) => {
    const embed = new EmbedBuilder();
    const response = await fetch('https://reddit.com/r/hoodironycentral/random/.json');
        const data = await response.json();

            const [list] = JSON.parse(data.body);
            const [post] = list.data.children;

            const permalink = post.data.permalink;
            const memeUrl = `https://reddit.com${permalink}`;
            const memeImage = post.data.url;
            const memeTitle = post.data.title;
            const memeUpvotes = post.data.ups;
            const memeNumComments = post.data.num_comments;

            embed.setTitle(`${memeTitle}`);
            embed.setURL(`${memeUrl}`);
            embed.setColor('Random');
            embed.setImage(memeImage);
            embed.setFooter({
                text:`👍 ${memeUpvotes} 💬 ${memeNumComments}`
            });

            channel.send({ embeds: [embed] });
        }};

Here is the console:

SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)
    at Object.run (file:///C:/x/v44bot/src/commands/reddit.js:13:24)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

TL;DR: I am trying to fetch a post from reddit, but it returns undefined.


Solution

  • The error is that you are trying to convert an already converted object, try this code

    import { EmbedBuilder, PermissionsBitField, SlashCommandBuilder } from "discord.js";
    import fetch from "node-fetch";
    
    export default {
        data: new SlashCommandBuilder()
          .setName("hoodclassic")
          .setDescription("haha so funny"),
          run: async (client, interaction) => {
        const embed = new EmbedBuilder();
        const response = await fetch('https://reddit.com/r/hoodironycentral/random/.json');
            const data = await response.json();
    
                const [post] = data.data.children;
    
                const permalink = post.data.permalink;
                const memeUrl = `https://reddit.com${permalink}`;
                const memeImage = post.data.url;
                const memeTitle = post.data.title;
                const memeUpvotes = post.data.ups;
                const memeNumComments = post.data.num_comments;
    
                embed.setTitle(`${memeTitle}`);
                embed.setURL(`${memeUrl}`);
                embed.setColor('Random');
                embed.setImage(memeImage);
                embed.setFooter({
                    text:`👍 ${memeUpvotes} 💬 ${memeNumComments}`
                });
    
                channel.send({ embeds: [embed] });
            }};