1

I'm working on an address book in python, and I'm trying to save the data (name, town & address) to a json file.

The problem's that when it saves to the json file, it creates a new object in the json file

example -

   {"Object1": {"Town": "town", "Address": "address"}}
   {"Object2": {"Town": "town", "Address": "address"}}

Because of that layout, I get this error whenever I try to do anything with it

Error -

    ValueError: Extra data: line 2 column 1 - line 2 column 55 (char 55 - 109) 

How can I make my json file layout something like this

Example -

    {"Object1": {"Town": "town", "Address": "address", "Object2": {"Town": "town", "Address": "address"}}

Here's my code -

import json

class Object:
    name = "Name"
    address = "Address"
    town = "Town"

    def return_info(self):
        dictionary = {self.name: {"Address": self.address, "Town": self.town}}
        return dictionary

    def __init__(self, entered_name, entered_town, entered_address):
        self.name = entered_name
        self.town = entered_town
        self.address = entered_address

def update(file):
    with open("data.json", "a") as outfile:
        json.dump(file, outfile)

new_object = Object("name", "town", "address")
update(new_object.return_info())
1
  • Why do you want to save object inside an object? Wouldn't you save list of objects instead? Commented Apr 22, 2015 at 6:41

2 Answers 2

4

You can just maintain all addresses in a dict and then dump into a json file.

addressmap = {
    "Object1": {"town": "town", "address": "address"},
    "Object2": {"town": "town", "address": "address"}
}

with open("addresses.json", "w") as f:
    json.dump(addressmap, f, indent=4)
Sign up to request clarification or add additional context in comments.

Comments

1

Your example of a desired object means having Object2 inside Object1, while it seems to me what you'd like is a list of your objects:

import json
dictlist = [{"Object1": {"Town": "town", "Address": "address"}},
            {"Object2": {"Town": "town", "Address": "address"}}]
with open("output.json", "w") as outfile:
  json.dump(dictlist, outfile)

3 Comments

This is sort of what I want.
But how could I then add/append to that
Something like how you do it with arrays - array.append()

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.