在渲染到模板时从删除键的键中删除引号

时间:2014-03-06 06:56:41

标签: python django django-templates

是否可以在使用render_to_string函数呈现字典时删除键上的引号,以便我在模板中获得key:value而不是'key':value

例如,如果这是我的词典:

d = {'a':1, 'b':2}

我像这样渲染它,

return render_to_string('somefile.json', {'d':d})

然后在somefile.json我将{{d}}作为{'a':1, 'b':2},但我希望{{d}}{a:1, b:2}。 (ab上没有引号)

我如何实现这一目标?

TIA

4 个答案:

答案 0 :(得分:2)

您可以使用的一种方法是覆盖__repr__类的dict方法或对其进行子类化并在那里更改方法。我在下面有一个后一个解决方案。

class MyDict(dict):
    def __repr__(self):
        s = "{"
        for key in self:
            s += "{0}:{1}, ".format(key, self[key])
        if len(s) > 1:
            s = s[0: -2]
        s += "}"
        return s

MyDict({'a': 1, 'b': 2})
{a:1, b:2}

答案 1 :(得分:1)

我发现Stepan的答案是准确有用的。在我的情况下,还可以递归地应用渲染,并在字符串元素上保留引号。此扩展版本也可能对其他人有用:

class DictWithoutQuotedKeys(dict):
    def __repr__(self):
        s = "{"
        for key in self:
            s += "{0}:".format(key)
            if isinstance(self[key], basestring):
                # String values still get quoted
                s += "\"{0}\", ".format(self[key])
            elif isinstance(self[key], dict):
                # Apply formatting recursively
                s += "{0}, ".format(DictWithoutQuotedKeys(self[key]))
            else:
                s += "{0}, ".format(self[key])
        if len(s) > 1:
            s = s[0: -2]
        s += "}"
        return s

答案 2 :(得分:0)

我发现John的解决方案很有用,对他的代码进行了一些调整以适合我的情况。要在字典和键中引用所有值而在字典中不使用引号

{
  "variant": {
    "id": 808950810,
    "option1": "Not Pink",
    "price": "99.00"
  }
}

收件人

{variant:{id:'32036302848074', compare_at_price:'39.83'}}
class DictWithoutQuotedKeys(dict):
    def __repr__(self):
        s = "{"
        for key in self:
            s += "{0}:".format(key)
            # if isinstance(self[key], str):
            #     # String values still get quoted
            #     s += "\"{0}\", ".format(self[key])
            # if isinstance(self[key], int):
            #     # String values still get quoted
            #     s += "\'{0}\', ".format(self[key])

            if isinstance(self[key], dict):
                # Apply formatting recursively
                s += "{0}, ".format(DictWithoutQuotedKeys(self[key]))
            else:
                # Quote all the values
                s += "\'{0}\', ".format(self[key])
        if len(s) > 1:
            s = s[0: -2]
        s += "}"
        return s

答案 3 :(得分:0)

调整了代码以处理嵌套列表和字典。
代码:

class DictWithoutQuotedKeys(dict):
def __repr__(self):
   # print(self)
    s = "{"
    
    for key in self:
        s += "{0}:".format(key)
        if isinstance(self[key], dict):
            # Apply formatting recursively
            s += "{0}, ".format(DictWithoutQuotedKeys(self[key]))
        elif isinstance(self[key], list):
            s +="["
            for l in self[key]:
                if isinstance(l, dict):
                    s += "{0}, ".format(DictWithoutQuotedKeys(l))
                else:
                    #print(l)
                    if isinstance(l, int):
                        s += "{0}, ".format(l)
                    else:
                        s += "'{0}', ".format(l)
            if len(s) > 1:
                s = s[0: -2]
            s += "], "
        else:
            if isinstance(self[key], int):
                s += "{0}, ".format(self[key])
            else:
                s += "\'{0}\', ".format(self[key])
            # Quote all the values
            #s += "\'{0}\', ".format(self[key])
    
    if len(s) > 1:
        s = s[0: -2]
    s += "}"
    return s

输入:

data = {'a':["1", "3", 4], 'b':[{'check1':9, 'check2':"kkk"}], 'c': {'d':2 , 'e': 3}, 'f':'dd', 't':2}

输出:

{a:['1', '3', 4], b:[{check1:9, check2:'kkk'}], c:{d:2, e:3}, f:'dd', t:2}