如何将JSON文件导入Django数据库?

时间:2014-10-11 18:33:19

标签: python json django postgresql django-views

我正在学习django和javascript。我有一个json文件具有以下语法:

{"business_id": "JwUE5GmEO-sH1FuwJgKBlQ", "full_address": "6162 US Highway 51\nDe Forest, WI 53532", "hours": {}, "open": true, "categories": ["Restaurants"], "city": "De Forest", "review_count": 26, "name": "Pine Cone Restaurant", "neighborhoods": [], "longitude": -89.335843999999994, "state": "WI", "stars": 4.0, "latitude": 43.238892999999997, "attributes": {"Take-out": true, "Good For": {"dessert": false, "latenight": false, "lunch": true, "dinner": false, "breakfast": false, "brunch": false}, "Caters": false, "Noise Level": "average", "Takes Reservations": false, "Delivery": false, "Ambience": {"romantic": false, "intimate": false, "touristy": false, "hipster": false, "divey": false, "classy": false, "trendy": false, "upscale": false, "casual": false}, "Parking": {"garage": false, "street": false, "validated": false, "lot": true, "valet": false}, "Has TV": true, "Outdoor Seating": false, "Attire": "casual", "Alcohol": "none", "Waiter Service": true, "Accepts Credit Cards": true, "Good for Kids": true, "Good For Groups": true, "Price Range": 1}, "type": "business"}

我想将其导入django数据库。我试过了:

def import_db(request):
    f = open('business_out.json', 'r')
    for jsonline in f:
        #yield json.loads(jsonline)
        data = serializers.serialize("json", jsonline)
        print data["business_id"]

localhost://import_db

在此行收到错误
data = serializers.serialize("json", jsonline) 
Uncaught TypeError: Cannot read property 'key-preview' of undefined klippy.js:163Class.keyup klippy.js:163wrapper.extend.$owner mootools-core.js:1367defn mootools-core.js:3970

1 个答案:

答案 0 :(得分:2)

serializers.serialize"翻译"将数据建模为JSON,但您需要反之亦然 - 将json加载到DB。

你需要这样的东西:

with open('business_out.json') as f:
    data = json.load(f)

然后你会得到一个包含数据的词典,你可以使用它。