2017-03-15 96 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'>

,一切都像预想的那样,以

相关问题