遍历JSON需要比我想要的更多的for循环

时间:2019-04-21 00:49:22

标签: python refactoring

我正在读取.json文件并解析一些数据以保存到对象中。我需要迭代的JSON中只有2000左右的项目,但是我目前正在运行的脚本花费的时间比我想要的要长得多。

data_file = 'v1/data/data.json'
user = User.objects.get(username='lsv')
format = Format(format='Limited')
format.save()
lost_cards = []
lost_cards_file = 'v1/data/LostCards.txt'

with open(data_file) as file:
    data = json.load(file)

for item in data:
    if item['model'] == 'cards.cardmodel':
        if len(Card.objects.filter(name=item['fields']['name'])) == 0:
            print(f"card not found: {item['fields']['name']}")
            lost_cards.append(item['fields']['name'])
        try:
            Rating(
                card=Card.objects.get(name=item['fields']['name'], set__code=item['fields']['set']),
                rating=item['fields']['rating'],
                reason=item['fields']['reason'],
                format=format,
                rator=user
            ).save()
        except Exception as e:
            print(e, item['fields']['name'], item['fields']['set'])
            break

with open(lost_cards_file, 'w') as file:
    file.write(str(lost_cards))

代码可以按预期运行,但所需时间比我想要的要长得多。我希望有一个内置的JSON或迭代器功能可以加快此过程。

1 个答案:

答案 0 :(得分:0)

有。它称为json模块。

with open(data_file, 'r') as input_file:
    dictionary_from_json = json.load(input_file)

应该这样做。

相关问题