Login

spaceless_json

Author:
dkoldyaev
Posted:
March 4, 2019
Language:
Python
Version:
Not specified
Score:
1 (after 1 ratings)

Now you can format and compress json-data in django template

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
from django.template.base import Node
    from django.template.library import Library
    
    register = Library()
    
    class SpacelessJsonNode(Node):
        def __init__(self, nodelist):
            self.nodelist = nodelist
    
        def render(self, context):
            import json, unicodedata
            content = self.nodelist.render(context).strip()
            content = unicodedata.normalize('NFKD', content)
            json_data = json.loads(content)
            return safestring.mark_safe(json.dumps(json_data, ensure_ascii=False))
    
    
    @register.tag(name='spaceless_json')
    def spaceless_json(parser, token):
        """
        Remove whitespace inside json-data.
    
        Example usage::
    
            <script type="application/id+json">
            {% spaceless_json %}
                {
                    "foo":  "bar",
    
                            "foo2":
                                    "bar2"
                }
            {% endspaceless_json %}
            </script>
    
        This example returns this string::
        
            <script type="application/id+json">{"foo":"bar", "foo2":"bar2"}</script>
        """
        nodelist = parser.parse(('endspaceless_json',))
        parser.delete_first_token()
        return SpacelessJsonNode(nodelist)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.