Bosen
Bosen

Reputation: 139

How to parse data from file Json or Excel

I got a code to parse data from json file but still it is incomplete.

{"people": [
{"UserID": "xxxxx123", "Name": "Steve", "Sex": "Male", "age": "30"},
{"UserID": "xxxxx124", "Name": "Rachel", "Sex": "Female", "age": "25"},
{"UserID": "xxxxx125", "Name": "George", "Sex": "Male", "age": "22"} ] }

@bot.command(pass_context=True)
async def mention(ctx, member: discord.Member):
  with open('data.txt') as json_file:
    data = json.load(json_file)
    for p in data['people']:
      if(p['UserID'] == str(member.id)):
        await bot.send_message(ctx.message.channel, p)

when we type ?mention @user in discord channel bot gives that user data. but i need 2 more help.

  1. bot needs to get data from multiple json files or from excel sheets 1 2 3 etc.
  2. rather than tagging user it should be ?mention xxxxx123 or ?mention George to get that user data.

Update error when i run in server:

Ignoring exception in on_ready
Traceback (most recent call last):
  File "/home/bosen/.local/lib/python3.6/site-packages/discord/client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "bot.py", line 37, in on_ready
    d = json.load(f)
  File "/home/bosen/.local/lib/python3.6/json/__init__.py", line 296, in load
    return loads(fp.read(),
  File "/home/bosen/.local/lib/python3.6/codecs.py", line 321, in decode
    (result, consumed) = self._buffer_decode(data, self.errors, final)
MemoryError

Upvotes: 0

Views: 267

Answers (1)

Patrick Haugh
Patrick Haugh

Reputation: 61042

I would re-index the list from the json into a dictionary with two indices: mapping both names and ids to lists of records.

import json
from collections import defaultdict

index = defaultdict(list)

@bot.event
async def on_ready():
    global index
    for filename in ('data1.json', 'data2.json'):
        with open(filename) as f:
            d = json.load(f)
            for record in d['people']:
                index[record['UserId'].lower()].append(record)
                index[record['Name'].lower()].append(record)

@bot.command(pass_context=True)
async def mention(ctx, *keys):
    for key in keys:
        for record in index[key]:
            await bot.say("{Name} is a {age} year old {Sex}  with id {UserId}".format(**record))

Upvotes: 1

Related Questions