0

I am trying to load simple objects from the json file. But i am getting error in it. below is my code and also the data in json format in db.txt file. I am calling the getAll() function of model.py from some other class.

file: model.py

import simplejson

class Person(object):
    def __init__(self, first_name = None, last_name = None):
        self.first_name = first_name
        self.last_name = last_name

    def name(self):
        return ("%s %s"%(self.first_name, self.last_name))

    @classmethod
    def getAll(self):
        database = open('db.txt', 'r')
        result = []
        json_list = simplejson.loads(database.read())
        print("json list {}".format(json_list))
        for item in json_list:
            print("item {}".format(item))
            print("type of item {}".format(type(item)))
            item = simplejson.loads(item)
            person = Person(item['first_name'], item['last_name'])
            result.append(person)
        return result

file: db.txt

[
    {
        "first_name":"first name",
        "last_name":"last name"
    },
    {
        "first_name":"first name 2",
        "last_name":"last name 2"
    }
]

ERROR (output):

json list [{'first_name': 'first name', 'last_name': 'last name'}, {'first_name': 'first name 2', 'last_name': 'last name 2'}]
item {'first_name': 'first name', 'last_name': 'last name'}
type of item <type 'dict'>
...
...
item = simplejson.loads(item)
...
...
KeyError: 0
6
  • why are you doing item = simplejson.loads(item)??? Commented Jun 21, 2019 at 21:42
  • @juanpa.arrivillaga because i want to extract first_name, last_name and create object Person from it. Commented Jun 21, 2019 at 21:43
  • That doesn't make sense .... Why are you passing a dict to .loads which requires a JSON-valid str....??? In any case that is the source of your error. Just use the dict. Commented Jun 21, 2019 at 21:44
  • @juanpa.arrivillaga then what is the best way to create json file for this requirement. Commented Jun 21, 2019 at 21:45
  • The JSON file is fine as it is. You can literally simply delete this line: item = simplejson.loads(item) and your code will work as you are expecting it to. I still don't understand why you think that line is necessary, or what it is supposed to do. Commented Jun 21, 2019 at 21:46

1 Answer 1

4

simplejson.loads(database.read()) parses the JSON all the way down. You don't need to do it at every level. Since item is already a dict, you can use it like one immediately.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.