我正在尝试将字典列表保存为JSON文件。该列表包含需要转换的日期时间对象,因此我将列表传递给json_data
变量,将日期时间更改为字符串,然后将其保存。
这是我添加新词典条目并保存的代码:
TODAY = datetime.date.today()
class Deck():
def __init__(self):
self.cards = []
def add(self, question, answer):
'''Create a new card'''
card = {
'question': question,
'answer': answer,
'date_added': TODAY,
'review_date': TODAY,
}
self.cards.append(card)
def save(self):
'''Save cards'''
json_data = []
for card in self.cards:
json_data.append(card)
for data in json_data:
data['date_added'] = data['date_added'].isoformat()
data['review_date'] = data['review_date'].isoformat()
with open('cards.json', 'w') as obj:
json.dump(json_data, obj)
文件保存正常,但由于某种原因self.cards
正在变更,而不是json_data
。我希望self.cards中的datetime对象保持这种状态。假设该实例名为deck
:
>>> deck.add('1 + 1',2)
>>> deck.cards[0]['date_added']
datetime.date(2017, 2, 12)
>>> deck.save()
>>> deck.cards[0]['date_added']
'2017-02-12'
>>> deck.save()
Traceback (most recent call last):
data['date_added'] = data['date_added'].isoformat()
AttributeError: 'str' object has no attribute 'isoformat'
不确定为什么会这样,我做了一些搜索,但找不到解决方案。我感谢任何协助。
答案 0 :(得分:1)
保存数据时,需要复制每张卡。否则,当您转换日期时,您仍然会修改原始卡片。
所以试试这个:
def save(self):
'''Save cards'''
json_data = []
for card in self.cards:
card = card.copy()
card['date_added'] = card['date_added'].isoformat()
card['review_date'] = card['review_date'].isoformat()
json_data.append(card)
with open('cards.json', 'w') as obj:
json.dump(json_data, obj)