Jonty Morris Jonty Morris - 1 year ago 87
JSON Question

Python exporting multiple data to a json file

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 = { {"Address": self.address, "Town":}}
return dictionary

def __init__(self, entered_name, entered_town, entered_address): = entered_name = 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")

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download