迭代django模板中的json数据

时间:2017-03-21 18:32:07

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

我在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模板中尝试循环时,我得到错误:

  

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

关于如何构造JSON,我将如何在django模板中循环它,因为以下内容不起作用。

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

1 个答案:

答案 0 :(得分:4)

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

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

供参考:

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