2013-12-17 14 views
2

我有以下的JSON:的Python:JSON不能序列

{ 
    u'objectid': u'427912', 
    u'fooditems': u'Cold Truck: Hamburger: cheeseburgers: hot dogs: hot sandwiches: cold sandwiches: egg muffins: cup of noodles: corn dogs: canned soup: coffee: hot cocoa: hot tea: gatorade: juice: milk: soda: water: fruits: fruit salad: rice pudding: yogurt: candy bars: chips: cookies: donuts: granola bars: muffins', 
    u'facilitytype': u'Truck', 
    u'priorpermit': u'1', 
    u'location': { 
     u'latitude': u'37.730906164188', 
     u'needs_recoding': False, 
     u'longitude': u'-122.373302577475' 
    }, 
    u'lot': u'008', 
    u'cnn': u'7253000', 
    u'status': u'APPROVED', 
    u'schedule': u'http://bsm.sfdpw.org/PermitsTracker/reports/report.aspx?title=schedule&report=rptSchedule&params=permit=13MFF-0072&ExportPDF=1&Filename=13MFF-0072_schedule.pdf', 
    u'locationdescription': u'INNES AVE: EARL ST to ARELIOUS WALKER DR (700 - 799)', 
    u'latitude': u'37.7309061503597', 
    u'blocklot': u'4644008', 
    u'address': u'Assessors Block 4644/Lot008', 
    u'approved': u'2013-04-04T08:44:08', 
    u'received': u'Mar 15 2013 10:24AM', 
    u'applicant': u"Park's Catering", 
    u'longitude': u'-122.373302577485', 
    u'expirationdate': u'2014-03-15T00:00:00', 
    u'permit': u'13MFF-0072', 
    u'y': u'2094023.408', 
    u'x': u'6019956.89', 
    u'_id': ObjectId('52afeb27e8de3f3174110041'), 
    u'block': u'4644' 
} 

當我打電話就可以了json.dumps(),我得到的錯誤raise TypeError(repr(o) + " is not JSON serializable")

我在做什麼錯?

+1

什麼是ObjectId? –

+0

這是mongo編號。刪除它後,我得到了它的工作。謝謝! – tldr

回答

2

您的字典中包含一個ObjectId()對象。

如果沒有特殊處理,該對象不可序列化。可以用原始值替換它,或者爲參數default提供一個函數來爲您編碼這些對象:

def objectid_default(obj): 
    if isinstance(obj, ObjectId): 
     return str(obj) # hex string version 
    raise TypeError(obj) 

json.dumps(d, default=objectid_default) 
0

鑑於您已經在您的評論中解決了問題,我將在此爲那些發現此問題並立即尋找答案的人發佈解決方案。

問題是Python中的某些對象不能輕易地序列化爲JSON,而ObjectId就是其中之一。 Python試圖將該對象轉換爲與JSON等效的對象,但不知道如何,因此會引發錯誤。解決方法是確保所有傳入json.dumps的值都可以正確編碼(在這種情況下,將_id轉換爲ObjectId並將其作爲字符串傳遞)。

相關問題