2013-02-13 69 views
2

如何在json文件中寫入我的數據?這是我的嘗試:如何在json文件中寫入我的數據?

from django.test import TestCase 
from django_dynamic_fixture import G 
import content.factories 
from django.core import serializers 
from content.models import UserProfile, Delivery 
from django.contrib.auth.models import User 

class DeliveryTest(TestCase): 
    def test_sample_data(self): 
     for i in range(0,10): 
      user = content.factories.UserFactory.create() 
      print user 
      for j in range(0, 50): 
       delivery = content.factories.DeliveryFactory.create(user=user) 
       print delivery 

       with open("file.json", "w") as out: 
        data = serializers.serialize("json", User.objects.all()) 

       with open("file.json", "w") as out: 
        data2 = serializers.serialize("json", Delivery.objects.all()) 

輸出(打印):http://dpaste.com/hold/923339/

回答

6

你實際上並沒有寫你的數據,只能轉換成JSON。在打開的文件調用.write()

with open("file.json", "w") as out: 
    data = serializers.serialize("json", User.objects.all()) 
    out.write(data) 
    data2 = serializers.serialize("json", Delivery.objects.all()) 
    out.write(data) 

只有開放file.json一次;每當您打開它以使用'w'模式進行書寫時,它將首先被擦除。

另外,get a reference to the serializer並告訴它來寫,直接打開文件:

with open("file.json", "w") as out: 
    json_serializer = serializers.get_serializer('json')() 
    json_serializer.serialize(User.objects.all(), stream=out) 
    json_serializer.serialize(Delivery.objects.all(), stream=out) 

這是更有效的。

+0

我寧願後面的例子。當你不需要它們時引入大量變量(data,data2,data3?)是一個壞習慣。幾乎與具有非常通用的變量名稱(如「數據」)一樣糟糕 – baloo 2013-02-13 17:19:20

+0

@baloo:我同意;但是在幫助某個人時,我希望儘可能重新使用他們的代碼,以便它可以被識別,並且他們可以更容易地看到丟失的東西。 :-) – 2013-02-13 17:20:19

+0

絕對,只是指出:) – baloo 2013-02-13 17:33:36

相關問題