json Python module questions. <SOLVED>

About writing shell scripts and making the most of your shell
Forum rules
Topics in this forum are automatically closed 6 months after creation.
Locked
Witch

json Python module questions. <SOLVED>

Post by Witch »

I'm trying to learn how to use json a Python module. But I'm having difficulties following and understanding this chapter where Hellmann talks about building my own Classes. I can't make the script work. Can somebody teach me this chapter?

http://www.doughellmann.com/PyMOTW/json ... -own-types

json_dump_default.py

Code: Select all

class MyObj(object):
    def __init__(self, s):
        self.s = s
    def __repr__(self):
        return '<MyObj(%s)>' % self.s


import json
import json_myobj

obj = json_myobj.MyObj('instance value goes here')

print 'First attempt'
try:
    print json.dumps(obj)
except TypeError, err:
    print 'ERROR:', err

def convert_to_builtin_type(obj):
    print 'default(', repr(obj), ')'
    # Convert objects to a dictionary of their representation
    d = { '__class__':obj.__class__.__name__, 
          '__module__':obj.__module__,
          }
    d.update(obj.__dict__)
    return d

print
print 'With default'
print json.dumps(obj, default=convert_to_builtin_type)

terminal

Code: Select all

$ python json_dump_default.py 

Traceback (most recent call last):
  File "json_dump_default.py", line 9, in <module>
    import json_myobj

ImportError: No module named json_myobj
Last edited by LockBot on Wed Dec 28, 2022 7:16 am, edited 2 times in total.
Reason: Topic automatically closed 6 months after creation. New replies are no longer allowed.
Locked

Return to “Scripts & Bash”