python simplejson decoding

Peter Otten __peter__ at web.de
Wed Mar 2 09:24:46 EST 2011


Arthur Mc Coy wrote:

> Hi all,
> 
> 
> 
> I'm trying an example (in attached file, I mean the bottom of this
> message).
> 
> First, I create a list of 3 objects. Then I do:
> 
> 
> PutJSONObjects(objects)
> objects = GetJSONObjects()
> PutJSONObjects(objects, "objects2.json")
> 
> 
> 1) PutJSONObjects(objects) method creates objects.json file (by
> default). It works fine.
> 2) Then objects = GetJSONObjects() method get the file contents and
> return.
> 
> 3) Finally the script fails on the third method
> PutJSONObjects(objects, "objects2.json")
> saying: AttributeError: 'dict' object has no attribute '__dict__'
> 
> 
> That is true, because objects returned by GetJSONObjects() is not a
> list of objects, but simple string....
> 
> So here is the question, please, how should I DECODE .json file into
> list of python objects so that I will be able to put the copy of these
> objects into a new file called objects2.json ?
> 
> simplejson docs are hard to follow - without examples.

I suggest that you use json instead which is part of the standard library 
since Python 2.6. The documentation is here:

http://docs.python.org/library/json.html

If you know that there are only MyObject instances you need a function to 
construct such a MyObject instance from a dictionary. You can then recreate 
the objects with

objects = [object_from_dict(d) for d in json.load(f)]

or, if all dictionaries correspond to MyObject instances

objects = json.load(f, object_hook=object_from_dict)

A general implementation for old-style objects (objects that don't derive 
from object) is a bit messy:

# idea copied from pickle.py
class Empty:
    pass

def object_from_dict(d):
    obj = Empty()
    obj.__class__ = MyObject
    obj.__dict__.update((str(k), v) for k, v in d.iteritems()) # *
    return obj

If you are willing to make MyClass a newstyle class with

class MyObject(object):
    # ...

the function can be simplified to

def object_from_dict(d):
    obj = object.__new__(MyObject)
    obj.__dict__.update((str(k), v) for k, v in d.iteritems()) # *
    return obj

(*) I don't know if unicode attribute names can do any harm, 
obj.__dict__.update(d) might work as well.




More information about the Python-list mailing list