【问题标题】:Iterating through json data in django template遍历 django 模板中的 json 数据
【发布时间】:2017-08-13 14:41:35
【问题描述】:

我在 django 模板中迭代 JSON 时遇到问题。

我的 JOSN 看起来像,

{
"main_cats": [
    {
        "pk": 1,
        "model": "BeeForms.maincategory",
        "fields": {
            "is_visible": true,
            "name": "Test Main",
            "order_by_asc": true,
            "base_category": 1,
            "help_text": "",
            "is_seller_field": false,
            "position": 10,
            "show_seller": true,
            "order_by_type": true
        }
    }
],
"sub_cats": [
    {
        "pk": 15,
        "model": "BeeForms.subcategory",
        "fields": {
            "regex": "[0-9a-zA-Z]",
            "library_id": "TextBox",
            "input_length": 255,
            "name": "TextBox",
            "order_by_asc": false,
            "field_type": "text",
            "main_category": 1,
            "is_active": true,
            "is_visible": true,
            "help_text": "",
            "position": 10,
            "is_required": true,
            "field_display_type": "input",
            "order_by_type": true,
            "has_enumerations": false
        }
    },
    {
        "pk": 16,
        "model": "BeeForms.subcategory",
        "fields": {
            "regex": "[A-Za-z0-9]",
            "library_id": "SelectBox",
            "input_length": 255,
            "name": "SelectBox",
            "order_by_asc": false,
            "field_type": "",
            "main_category": 1,
            "is_active": true,
            "is_visible": true,
            "help_text": "",
            "position": 10,
            "is_required": false,
            "field_display_type": "select",
            "order_by_type": true,
            "has_enumerations": true
        }
    },
    {
        "pk": 18,
        "model": "BeeForms.subcategory",
        "fields": {
            "regex": "[0-9a-zA-Z]",
            "library_id": "TextArea",
            "input_length": 255,
            "name": "TextArea",
            "order_by_asc": false,
            "field_type": "varchar",
            "main_category": 1,
            "is_active": true,
            "is_visible": true,
            "help_text": "",
            "position": 10,
            "is_required": false,
            "field_display_type": "textarea",
            "order_by_type": true,
            "has_enumerations": false
        }
    },
    {
        "pk": 22,
        "model": "BeeForms.subcategory",
        "fields": {
            "regex": "[A-Za-z0-9]",
            "library_id": "Checkbox",
            "input_length": 255,
            "name": "Checkbox",
            "order_by_asc": false,
            "field_type": "",
            "main_category": 1,
            "is_active": true,
            "is_visible": true,
            "help_text": "",
            "position": 10,
            "is_required": false,
            "field_display_type": "checkbox",
            "order_by_type": true,
            "has_enumerations": true
        }
    }
],
"base_cats": [
    {
        "pk": 1,
        "model": "BeeForms.basecategory",
        "fields": {
            "form_type": 1,
            "position": 10,
            "order_by_asc": true,
            "name": "Sales Information",
            "order_by_type": true
        }
    },
    {
        "pk": 2,
        "model": "BeeForms.basecategory",
        "fields": {
            "form_type": 1,
            "position": 20,
            "order_by_asc": true,
            "name": "Listing information",
            "order_by_type": true
        }
    },
    {
        "pk": 3,
        "model": "BeeForms.basecategory",
        "fields": {
            "form_type": 1,
            "position": 30,
            "order_by_asc": true,
            "name": "Land & Tax",
            "order_by_type": true
        }
    },
    {
        "pk": 4,
        "model": "BeeForms.basecategory",
        "fields": {
            "form_type": 1,
            "position": 40,
            "order_by_asc": true,
            "name": "Exterior Construction",
            "order_by_type": true
        }
    },
    {
        "pk": 5,
        "model": "BeeForms.basecategory",
        "fields": {
            "form_type": 1,
            "position": 50,
            "order_by_asc": true,
            "name": "Interior/Utilities",
            "order_by_type": true
        }
    },
    {
        "pk": 6,
        "model": "BeeForms.basecategory",
        "fields": {
            "form_type": 1,
            "position": 60,
            "order_by_asc": true,
            "name": "HOA/Community",
            "order_by_type": true
        }
    },
    {
        "pk": 7,
        "model": "BeeForms.basecategory",
        "fields": {
            "form_type": 1,
            "position": 70,
            "order_by_asc": true,
            "name": "Remarks",
            "order_by_type": true
        }
    }
],
"enum_content": [
    {
        "pk": 58,
        "model": "BeeForms.enumerationcontent",
        "fields": {
            "library_id": "SelectYesA1",
            "name": "SelectYesA1",
            "order_by_asc": false,
            "is_visible": true,
            "is_active": true,
            "enum_type_category": 53,
            "position": 10,
            "order_by_type": true
        }
    },
    {
        "pk": 59,
        "model": "BeeForms.enumerationcontent",
        "fields": {
            "library_id": "SelectNoA1",
            "name": "SelectNoA1",
            "order_by_asc": false,
            "is_visible": true,
            "is_active": true,
            "enum_type_category": 53,
            "position": 10,
            "order_by_type": true
        }
    },
    {
        "pk": 60,
        "model": "BeeForms.enumerationcontent",
        "fields": {
            "library_id": "SelectCheckBoxYes",
            "name": "SelectCheckBoxYes",
            "order_by_asc": false,
            "is_visible": true,
            "is_active": true,
            "enum_type_category": 54,
            "position": 10,
            "order_by_type": true
        }
    },
    {
        "pk": 61,
        "model": "BeeForms.enumerationcontent",
        "fields": {
            "library_id": "SelectCheckBoxNo",
            "name": "SelectCheckBoxNo",
            "order_by_asc": false,
            "is_visible": true,
            "is_active": true,
            "enum_type_category": 54,
            "position": 10,
            "order_by_type": true
        }
    }
],
"enums": [
    {
        "pk": 20,
        "model": "BeeForms.enumerations",
        "fields": {
            "library_id": "SelectYes",
            "name": "SelectYes",
            "order_by_asc": false,
            "is_visible": true,
            "has_type": true,
            "is_active": true,
            "position": 10,
            "order_by_type": true,
            "sub_category": 16
        }
    },
    {
        "pk": 21,
        "model": "BeeForms.enumerations",
        "fields": {
            "library_id": "SelectNo",
            "name": "SelectNo",
            "order_by_asc": false,
            "is_visible": true,
            "has_type": true,
            "is_active": true,
            "position": 10,
            "order_by_type": true,
            "sub_category": 16
        }
    },
    {
        "pk": 30,
        "model": "BeeForms.enumerations",
        "fields": {
            "library_id": "Yes",
            "name": "Yes",
            "order_by_asc": false,
            "is_visible": true,
            "has_type": true,
            "is_active": true,
            "position": 10,
            "order_by_type": true,
            "sub_category": 22
        }
    },
    {
        "pk": 31,
        "model": "BeeForms.enumerations",
        "fields": {
            "library_id": "No",
            "name": "No",
            "order_by_asc": false,
            "is_visible": true,
            "has_type": false,
            "is_active": true,
            "position": 10,
            "order_by_type": true,
            "sub_category": 22
        }
    }
],
"enum_types": [
    {
        "pk": 53,
        "model": "BeeForms.enumerationtype",
        "fields": {
            "regex": "[A-Za-z0-9]",
            "is_visible": true,
            "name": "SelectYesA",
            "library_id": "SelectYesA",
            "field_type": "",
            "is_active": true,
            "has_content": true,
            "enum_category": 20,
            "field_display_type": "select",
            "input_length": 255
        }
    },
    {
        "pk": 54,
        "model": "BeeForms.enumerationtype",
        "fields": {
            "regex": "[A-Za-z0-9]",
            "is_visible": true,
            "name": "",
            "library_id": "",
            "field_type": "",
            "is_active": true,
            "has_content": true,
            "enum_category": 21,
            "field_display_type": "checkbox",
            "input_length": 255
        }
    }
]
}

我用来创建json文件的代码如下。

    def serialize(self, instance_name, form, destination):
    """ Seralizes the information passed in."""

    # we need to make sure that the directory is real.
    if not os.path.exists(destination):
        os.makedirs(destination)

    # Lets grab all the information needed and serailize it all at the same time.
    base_cats = serializers.serialize('json', BaseCategory.objects.all().filter(form_type_id=form.id).order_by('id'))
    main_cats = serializers.serialize('json', MainCategory.objects.all().order_by('id'))
    sub_cats = serializers.serialize('json', SubCategory.objects.all().order_by('id'))
    enums = serializers.serialize('json', Enumerations.objects.all().order_by('id'))
    enum_types = serializers.serialize('json', EnumerationType.objects.all().order_by('id'))
    enum_content = serializers.serialize('json', EnumerationContent.objects.all().order_by('id'))

    # now that they are all serailized make it into a list of simplejson
    base_list = simplejson.loads(base_cats)
    main_list = simplejson.loads(main_cats)
    sub_list = simplejson.loads(sub_cats)
    enums_list = simplejson.loads(enums)
    enum_type_list = simplejson.loads(enum_types)
    enum_content_list = simplejson.loads(enum_content)

    # now we combine them all together...
    self.json_data = simplejson.dumps({'base_cats': base_list, 'main_cats': main_list, 'sub_cats': sub_list,
                                       'enums': enums_list, 'enum_types': enum_type_list,
                                       'enum_content': enum_content_list}, indent=4)

    print(self.json_data)

    # now that we combined them into json_data. Lets write it out to a file.
    with open(destination + instance_name + '.json', 'w') as json_write:
        json_write.write(self.json_data)

我使用以下内容将 JSON 加载到 Python 对象中。

with open(instance_location + '.json', 'r') as json_read:
        self.json_data = json_read.read()

# now lets take the data and load into json array
data = simplejson.loads(self.json_data)

# now lets grab each list.
base_cats = data['base_cats']
main_cats = data['main_cats']
sub_cats = data['sub_cats']
enums = data['enums']
enum_types = data['enum_types']
enum_content = data['enum_content']

# lets return it all!
return base_cats, main_cats, sub_cats, enums, enum_types, enum_content

在直接的 Python 中,我可以遍历(例如 base_cats)并通过以下 for 循环获取我需要的信息

for base in base_dict:
    print base['pk']
    print base['fields']['name']

当我在 django 模板中尝试 for 循环时,出现以下错误:

无法解析余数:'['pk']' from 'base['pk']'

随着 JSON 的结构化方式,我将如何在 django 模板中循环遍历它,因为以下内容不起作用。

{% for base in base_cats %}
    {{ base['pk'] }}
{% endfor %}

【问题讨论】:

    标签: python json django django-models django-templates


    【解决方案1】:

    在模板中使用点运算符访问字段,而不是括号:

    {% for base in base_cats %}
        {{ base.pk }}
    {% endfor %}
    

    供参考:

    https://docs.djangoproject.com/en/1.10/ref/templates/language/#template-variables

    【讨论】:

    • 感谢您的帮助
    • @crzyone9584 如果答案解决了你的问题,你可以考虑接受它。
    • @MosesKoledoye 我明白这一点。我刚刚读完链接的页面并使用它。在告诉我将某些内容标记为答案之前,您能否给我一些时间实际将其标记为答案?
    • 最后修复 ['fields]'['name'] 的最后一个问题,您只需使用 base.fields.name
    • @crzyone9584 是的,你明白了。 :)
    猜你喜欢
    • 1970-01-01
    • 2016-08-13
    • 2018-02-24
    • 2011-07-16
    • 2018-05-24
    • 2016-11-12
    • 2019-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多