简体   繁体   中英

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 = {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())

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)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM