How Could I convert a JSON object to image object?

Viewed 123

I've attempted to look this solution up many times, however none of them work. Trying to make a discord bot that uses a JSON storage system. The bot is made in python. I'll show the code where I've tried multiple ways to display a image from the JSON storage. Even Utf-8 and 16 encoding didn't work. So I've randomly been trying just about anything now. It is like this ->

{
  "id": 1,
  "Name": "bulbasaur",
  "Image": "https://i.imgur.com/MOQHxZGg.png"
}

JSON above

Python below
@commands.command(name='image_test')
    async def image(self, context,  arg):
        with open('image.json') as image:
            p = json.load(image)
        p['Name'] = arg
        #print(p['Name'])
        #print(p['Image'])

        #with urllib2.urlopen(p['Image']) as i:
            #data = i.read().decode('ISO-8859-1')


        embed = discord.Embed()
        embed.title = 'test image'
        embed.set_image(url=requests.get(p['Image']).url)
        await context.channel.send(embed=embed)

1 Answers

When a JSON object is loaded into python, it behaves exactly like a dictionary, with values that can be accessed with keys:

>>> mydict = {"foo": "bar"}
>>> mydict["foo"]
bar

The embed's images work purely off of a URL in a string that leads to the source image. You already have the image's URL stored in the json, so all you need to do is use the right key ("Image") to access its URL for the embed:

    @commands.command(name='image_test')
    async def image(self, context,  arg):

        with open('image.json') as image:
            p = json.load(image)

        embed = discord.Embed()
        embed.title = 'test image'
        embed.set_image(url=p['Image'])
        await context.send(embed=embed) # edited to use context.send()

As a side-note, one thing I noticed was your use of context.channel.send().
The Context object inherits from abc.Messageable, meaning that you can directly call the send() coroutine to send a message to the channel.


References:

Related