2017-03-15 93 views
0

我有一個相當大的字典,看起來像這樣:字符串索引必須是整數 - Django的

{ 
'startIndex': 1, 
'username': '[email protected]', 
'items': [{ 
    'id': '67022006', 
    'name': 'Adopt-a-Hydrant', 
    'kind': 'analytics#accountSummary', 
    'webProperties': [{ 
     'id': 'UA-67522226-1', 
     'name': 'Adopt-a-Hydrant', 
     'websiteUrl': 'https://www.udemy.com/, 
     'internalWebPropertyId': '104343473', 
     'profiles': [{ 
      'id': '108333146', 
      'name': 'Adopt a Hydrant (Udemy)', 
      'type': 'WEB', 
      'kind': 'analytics#profileSummary' 
     }, { 
      'id': '132099908', 
      'name': 'Unfiltered view', 
      'type': 'WEB', 
      'kind': 'analytics#profileSummary' 
     }], 
     'level': 'STANDARD', 
     'kind': 'analytics#webPropertySummary' 
    }] 
}, { 
    'id': '44222959', 
    'name': 'A223n', 
    'kind': 'analytics#accountSummary', 

And so on.... 

當我複製我的Jupyter筆記本本字典,我跑我在我的Django的代碼運行完全相同的功能它按預期運行,所有東西都是一樣的,在我的django代碼中,我甚至可以打印出字典,然後將其複製到筆記本中,然後運行它並獲得我期望的結果。

只是更多的信息,這是功能:

google_profile = gp.google_profile # Get google_profile from DB 
print(google_profile) 
all_properties = [] 
for properties in google_profile['items']: 
    all_properties.append(properties) 

site_selection=[] 
for single_property in all_properties: 
    single_propery_name=single_property['name'] 
    for single_view in single_property['webProperties'][0]['profiles']: 
     single_view_id = single_view['id'] 
     single_view_name = (single_view['name']) 
     selections = single_propery_name + ' (View: '+single_view_name+' ID: '+single_view_id+')' 
     site_selection.append(selections) 
print (site_selection) 

所以我的猜測是,我的筆記本有某種JS​​ON解析器安裝或類似的東西嗎?那可能嗎?爲什麼在Django中,我無法像使用ipython筆記本一樣訪問字典?

編輯

更多信息: 的錯誤是在該行:for properties in google_profile['items']: Django的調試是:TypeError at /gconnect/ string indices must be integers

本地變量是:

all_properties =[] 
current_user = '[email protected]' 
google_profile = `the above dictionary` 
+0

函數中的哪個位置發生錯誤?你能顯示實際的錯誤信息嗎? –

+0

嘿@ScottHunter我已經添加了更多信息,謝謝 – Costantin

+0

google_profile是一個字符串,所以你不能使用['items'],這隻適用於dicts,defaultdicts和OrderedDicts或類實現__getitem__ –

回答

0

所以剛纔講清楚誰發現這個問題:

如果您在數據庫中保存字典,django會將其保存爲字符串,因此您將無法訪問它。

爲了解決這個問題,你可以將它重新轉換爲詞典:

this post答案完全爲我工作,換句話說:

import json 
s = "{'muffin' : 'lolz', 'foo' : 'kitty'}" 
json_acceptable_string = s.replace("'", "\"") 
d = json.loads(json_acceptable_string) 
# d = {u'muffin': u'lolz', u'foo': u'kitty'} 

有很多方法可以將字符串轉換爲一本字典,這只是一個。如果你在這個問題迷迷糊糊,你可以快速檢查,如果它是一個字符串,而不是一本字典的搭配:

print(type(var)) 

在我來說,我有:

<class 'str'>

上面的方法轉換之前和後來我

<class 'dict'>

,一切都像預想的那樣,以

相關問題