Python将多个数据导出到json文件

时间:2015-04-22 06:38:10

标签: python json python-3.x

我在python中处理地址簿,我试图将数据(名称,城镇和地址)保存到json文件中。

问题是当它保存到json文件时,它会在json文件中创建一个新对象

示例 -

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

由于这种布局,每当我尝试用它做任何事情时都会收到此错误

错误 -

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

如何使我的json文件布局像这样

示例 -

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

这是我的代码 -

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

2 个答案:

答案 0 :(得分:4)

您可以只维护dict中的所有地址,然后转储到json文件中。

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

with open("addresses.json", "w") as f:
    json.dump(addressmap, f, indent=4)

答案 1 :(得分:1)

您所需对象的示例意味着在Object2内部Object1,而在我看来,您想要的是对象列表:

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