Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {
- "type": "Person",
- "firstName": "John",
- "lastName": "Smith",
- "address": {
- "streetAddress": "21 2nd Street",
- "city": "New York",
- "state": "NY",
- "postalCode": 10021
- },
- "phoneNumbers": [
- "212 555-1234",
- "646 555-4567"
- ]
- }
- if not json_object.has_key('type'):
- raise TypeError('JSON stream is missing a "type" attribute.')
- ##### THIS IS WHERE I WANT TO CHECK IF THE TYPE BY THAT NAME EXISTS ALREADY ####
- # create a type definition and add attributes to it
- definition = type(json_object['type'], (object,), {})
- for key in json_object.keys():
- setattr(definition, key, None)
- # instantiate and populate a test object
- tester = definition()
- for key, value in json_object.iteritems():
- setattr(tester, key, value)
- import types
- listOfClasses = [cls for cls in globals().values() if type(cls) == types.ClassType]
- json_types = {}
- def get_json_type(name):
- try:
- return json_types[name]
- except KeyError:
- json_types[name] = t = type(json_object['type'], (object,), {})
- # any further initialization of t here
- return t
- definition = get_json_type(json_object['type'])
- tester = definition()
- # or: tester = get_json_type(json_object['type'])()
- json_types = globals()
- Python 2.5.2 (r252:60911, Oct 5 2008, 19:29:17)
- [GCC 4.3.2] on linux2
- Type "help", "copyright", "credits" or "license" for more information.
- >>> dir()
- ['__builtins__', '__doc__', '__name__']
- >>> class Foo:
- ... pass
- ...
- >>> dir()
- ['Foo', '__builtins__', '__doc__', '__name__']
- >>> type(eval('Foo'))
- <type 'classobj'>
Add Comment
Please, Sign In to add comment