In [1]:
import csv
import pprint
import json

rdr = csv.DictReader(open('party.csv'))

party = {}
for character in rdr:
    party[character['name']] = character

In [3]:
for name in party:
    party[name]['level'] = int(party[name]['level'])
    party[name]['equipment'] = []
    for i in range(1,4):
        itm = {}
        for field in ('name', 'quantity', 'weight each', 'cost', 'magic',
                      'materials', 'notes'):
            orig_field = 'equip %d %s' % (i, field)
            itm[field] = party[name].pop(orig_field)
        party[name]['equipment'].append(itm)
            
        party[name]['equipment'].append({
            'name': party[name]['magic item %d' % (i + 1)],
            'bonus': party[name]['magic item %d bonus' % (i + 1)],
            'description': party[name]['magic item %d description' % (i + 1)],
        })
    for i in range(2):
        party[name]['weapons'].append({
            'name': party[name]['weapon %d name' % (i + 1)],
            'damage': party[name]['weapon %d damage' % (i + 1)],
            'materials': party[name]['weapon %d materials' % (i + 1)].split(', '),
        })
    for field in list(party[name].keys()):
        try:
            party[name][field] = int(party[name][field])
        except (TypeError, ValueError):
            pass
        if field.startswith('weapon ') or field.startswith('magic item '):
            party[name].pop(field)


---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-c122fb5830d9> in <module>()
     11 
     12         party[name]['equipment'].append({
---> 13             'name': party[name]['magic item %d' % (i + 1)],
     14             'bonus': party[name]['magic item %d bonus' % (i + 1)],
     15             'description': party[name]['magic item %d description' % (i + 1)],

KeyError: 'magic item 2'

In [70]:
pprint.pprint(party)


{'Aelfryth': {'charisma': 14,
              'class': 'Thane',
              'constitution': 15,
              'dexterity': 15,
              'intelligence': 11,
              'level': 5,
              'magic items': [{'bonus': '',
                               'description': 'Burned in any lamp, its light '
                                              'reveals illusions, invisible '
                                              'creatures, and disguises',
                               'name': 'oil of revelation'},
                              {'bonus': '+1',
                               'description': '',
                               'name': 'bow'}],
              'name': 'Aelfryth',
              'strength': 16,
              'weapons': [{'damage': 'd8',
                           'materials': ['iron'],
                           'name': 'sword'},
                          {'damage': 'd6',
                           'materials': ['wood'],
                           'name': 'bow'}],
              'wisdom': 14},
 'Ethelred': {'charisma': 12,
              'class': 'Warband member',
              'constitution': 16,
              'dexterity': 11,
              'intelligence': 9,
              'level': 4,
              'magic items': [{'bonus': '+1',
                               'description': '',
                               'name': 'shield'},
                              {'bonus': '', 'description': '', 'name': ''}],
              'name': 'Ethelred',
              'strength': 17,
              'weapons': [{'damage': 'd8',
                           'materials': ['iron', 'wood'],
                           'name': 'battleaxe'},
                          {'damage': 'd4',
                           'materials': ['iron'],
                           'name': 'dagger'}],
              'wisdom': 7},
 'Imitrex': {'charisma': 11,
             'class': 'Sourceror',
             'constitution': 12,
             'dexterity': 14,
             'intelligence': 17,
             'level': 5,
             'magic items': [{'bonus': '',
                              'description': 'Placed to the ear, translates '
                                             'unknown languages.',
                              'name': 'horn of babel'},
                             {'bonus': '', 'description': '', 'name': ''}],
             'name': 'Imitrex',
             'strength': 8,
             'weapons': [{'damage': 'd6',
                          'materials': ['wood'],
                          'name': 'staff'},
                         {'damage': '', 'materials': [''], 'name': ''}],
             'wisdom': 11},
 'Xanax': {'charisma': 10,
           'class': 'Runaway thrall',
           'constitution': 14,
           'dexterity': 15,
           'intelligence': 12,
           'level': 3,
           'magic items': [{'bonus': '',
                            'description': 'A silver spoon that turns green on '
                                           'contact with poison',
                            'name': 'spoon of truth'},
                           {'bonus': '', 'description': '', 'name': ''}],
           'name': 'Xanax',
           'strength': 14,
           'weapons': [{'damage': 'd6',
                        'materials': ['wood'],
                        'name': 'cudgel'},
                       {'damage': 'd4',
                        'materials': ['iron'],
                        'name': 'knife'}],
           'wisdom': 9}}

In [77]:
p2 = []
for name in party:
    party[name]['_id'] = party[name]['name']
    p2.append(party[name])

In [78]:
p2


Out[78]:
[{'_id': 'Aelfryth',
  'charisma': 14,
  'class': 'Thane',
  'constitution': 15,
  'dexterity': 15,
  'intelligence': 11,
  'level': 5,
  'magic items': [{'bonus': '',
    'description': 'Burned in any lamp, its light reveals illusions, invisible creatures, and disguises',
    'name': 'oil of revelation'},
   {'bonus': '+1', 'description': '', 'name': 'bow'}],
  'name': 'Aelfryth',
  'strength': 16,
  'weapons': [{'damage': 'd8', 'materials': ['iron'], 'name': 'sword'},
   {'damage': 'd6', 'materials': ['wood'], 'name': 'bow'}],
  'wisdom': 14},
 {'_id': 'Ethelred',
  'charisma': 12,
  'class': 'Warband member',
  'constitution': 16,
  'dexterity': 11,
  'intelligence': 9,
  'level': 4,
  'magic items': [{'bonus': '+1', 'description': '', 'name': 'shield'},
   {'bonus': '', 'description': '', 'name': ''}],
  'name': 'Ethelred',
  'strength': 17,
  'weapons': [{'damage': 'd8',
    'materials': ['iron', 'wood'],
    'name': 'battleaxe'},
   {'damage': 'd4', 'materials': ['iron'], 'name': 'dagger'}],
  'wisdom': 7},
 {'_id': 'Xanax',
  'charisma': 10,
  'class': 'Runaway thrall',
  'constitution': 14,
  'dexterity': 15,
  'intelligence': 12,
  'level': 3,
  'magic items': [{'bonus': '',
    'description': 'A silver spoon that turns green on contact with poison',
    'name': 'spoon of truth'},
   {'bonus': '', 'description': '', 'name': ''}],
  'name': 'Xanax',
  'strength': 14,
  'weapons': [{'damage': 'd6', 'materials': ['wood'], 'name': 'cudgel'},
   {'damage': 'd4', 'materials': ['iron'], 'name': 'knife'}],
  'wisdom': 9},
 {'_id': 'Imitrex',
  'charisma': 11,
  'class': 'Sourceror',
  'constitution': 12,
  'dexterity': 14,
  'intelligence': 17,
  'level': 5,
  'magic items': [{'bonus': '',
    'description': 'Placed to the ear, translates unknown languages.',
    'name': 'horn of babel'},
   {'bonus': '', 'description': '', 'name': ''}],
  'name': 'Imitrex',
  'strength': 8,
  'weapons': [{'damage': 'd6', 'materials': ['wood'], 'name': 'staff'},
   {'damage': '', 'materials': [''], 'name': ''}],
  'wisdom': 11}]

In [79]:
with open('party.json', 'w') as outfile:
    json.dump(p2, outfile, indent=2)

In [80]:
cat party.json


[
  {
    "weapons": [
      {
        "name": "sword",
        "materials": [
          "iron"
        ],
        "damage": "d8"
      },
      {
        "name": "bow",
        "materials": [
          "wood"
        ],
        "damage": "d6"
      }
    ],
    "wisdom": 14,
    "class": "Thane",
    "intelligence": 11,
    "constitution": 15,
    "magic items": [
      {
        "bonus": "",
        "name": "oil of revelation",
        "description": "Burned in any lamp, its light reveals illusions, invisible creatures, and disguises"
      },
      {
        "bonus": "+1",
        "name": "bow",
        "description": ""
      }
    ],
    "dexterity": 15,
    "level": 5,
    "name": "Aelfryth",
    "charisma": 14,
    "_id": "Aelfryth",
    "strength": 16
  },
  {
    "weapons": [
      {
        "name": "battleaxe",
        "materials": [
          "iron",
          "wood"
        ],
        "damage": "d8"
      },
      {
        "name": "dagger",
        "materials": [
          "iron"
        ],
        "damage": "d4"
      }
    ],
    "wisdom": 7,
    "class": "Warband member",
    "intelligence": 9,
    "constitution": 16,
    "magic items": [
      {
        "bonus": "+1",
        "name": "shield",
        "description": ""
      },
      {
        "bonus": "",
        "name": "",
        "description": ""
      }
    ],
    "dexterity": 11,
    "level": 4,
    "name": "Ethelred",
    "charisma": 12,
    "_id": "Ethelred",
    "strength": 17
  },
  {
    "weapons": [
      {
        "name": "cudgel",
        "materials": [
          "wood"
        ],
        "damage": "d6"
      },
      {
        "name": "knife",
        "materials": [
          "iron"
        ],
        "damage": "d4"
      }
    ],
    "wisdom": 9,
    "class": "Runaway thrall",
    "intelligence": 12,
    "constitution": 14,
    "magic items": [
      {
        "bonus": "",
        "name": "spoon of truth",
        "description": "A silver spoon that turns green on contact with poison"
      },
      {
        "bonus": "",
        "name": "",
        "description": ""
      }
    ],
    "dexterity": 15,
    "level": 3,
    "name": "Xanax",
    "charisma": 10,
    "_id": "Xanax",
    "strength": 14
  },
  {
    "weapons": [
      {
        "name": "staff",
        "materials": [
          "wood"
        ],
        "damage": "d6"
      },
      {
        "name": "",
        "materials": [
          ""
        ],
        "damage": ""
      }
    ],
    "wisdom": 11,
    "class": "Sourceror",
    "intelligence": 17,
    "constitution": 12,
    "magic items": [
      {
        "bonus": "",
        "name": "horn of babel",
        "description": "Placed to the ear, translates unknown languages."
      },
      {
        "bonus": "",
        "name": "",
        "description": ""
      }
    ],
    "dexterity": 14,
    "level": 5,
    "name": "Imitrex",
    "charisma": 11,
    "_id": "Imitrex",
    "strength": 8
  }
]

In [84]:
!mongoimport -d party -c characters --file party.json --jsonArray


connected to: 127.0.0.1
2015-09-12T14:44:27.334-0400 imported 4 objects

In [85]:
cat show_one.js


db.characters.findOne({'name': 'Xanax'});

In [87]:
!mongo party show_one.js


MongoDB shell version: 2.6.3
connecting to: party

Who carries wooden weapons?


In [ ]:


In [4]:
import json
import psycopg2
conn = psycopg2.connect('dbname=dnd user=dungeonmaster password=gygax')
curs = conn.cursor()
with open('data/party.json') as infile:
    for character in json.load(infile):
        curs.execute("INSERT INTO party (character) VALUES (%s)", (json.dumps(character),))
conn.commit()
conn.close()