繁体   English   中英

字符串索引必须是整数-Django

[英]String indices must be integers - Django

我有一本很大的字典,看起来像这样:

{
'startIndex': 1,
'username': 'myemail@gmail.com',
'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)

所以我的猜测是我的笔记本安装了某种json解析器或类似的东西? 那可能吗? 为什么在django中我无法像在ipython笔记本上一样访问字典?

EDITS

更多信息:错误所在: for properties in google_profile['items']: Django调试为: TypeError at /gconnect/ string indices must be integers

本地变量是:

all_properties =[]
current_user = 'myemail@gmail.com'
google_profile  = `the above dictionary`

因此,为了明确说明谁发现了这个问题:

如果您将字典保存在数据库中,则django会将其保存为字符串,因此以后将无法访问它。

为了解决这个问题,您可以将其重新转换为字典:

这篇文章的答案对我来说是完美的,换句话说:

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'>

一切都按预期进行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM