python simplejson decoding

Arthur Mc Coy 1984docmccoy at gmail.com
Wed Mar 2 08:13:25 EST 2011


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.



Please, help me. Be happy!

Arthur

--------

# Python-JSON method for caching my objects.

import simplejson as json
import os.path
from datetime import datetime


def GetJSONObjects():

    # determine the json data file path
    filename = "objects.json"
    filepath = "/home/docmccoy/Documents/" + filename
    if os.path.isfile(filepath):
        filename = filepath
        f = open(filename, 'r')
        objects = json.load( f )
        print objects
    else:
        objects = list()

    return objects


def PutJSONObjects(objects, filename = "objects.json"):

    # determine the json data file path
    filepath = "/home/docmccoy/Documents/" + filename
    if os.path.isfile(filepath):
        filename = filepath

    f = open(filename, 'w')
    json.dump([o.__dict__ for o in objects], f, indent = 4 * ' ' )


class MyObject:
    def __init__(self, ID, url, category, osfamily, createDate):
        self.id = ID
        self.url = url
        self.category = category
        self.osfamily = osfamily
        self.createDate = createDate


o1 = MyObject(1, "http://google.com", "search", "linux",
unicode(datetime.now()))
o2 = MyObject(2, "http://localhost", "mycomp", None,
unicode(datetime.now()))
o3 = MyObject(3, "http://milan.com", "football", "windows",
unicode(datetime.now()))

objects = list()
objects.append(o1)
objects.append(o2)
objects.append(o3)

PutJSONObjects(objects)
objects = GetJSONObjects()
PutJSONObjects(objects, "objects2.json")



More information about the Python-list mailing list