Decode json and Iterate through items in django template

后端 未结 2 1974
孤街浪徒
孤街浪徒 2020-12-29 14:40

Hi I am using simplejson to import some json and then decode for use within a django template,

this is the decoded json:

{u\'ServerID\': 1, u\'Cache\         


        
相关标签:
2条回答
  • 2020-12-29 15:20

    You don't need to do any further pre-processing in Python before sending the dictionary to Django (beyond what you have already done; using simplejson to parse the JSON string into a dictionary). Django's templating system is very good at dealing with dictionaries and lists.

    I will assume you have passed the dictionary to Django in a variable called obj.

    You should be able to access each item in the Result part of the dictionary using a for loop:

    <ul>
    {% for result in obj.Result %}
        <li>{{ result.Url }}, {{ result.PlaylistID }}, {{ result.Name }}</li>
    {% endfor %}
    </ul>
    

    For example, will place the results in a bulleted list, with the Url, Playlist and Name in a comma-separated list.

    0 讨论(0)
  • 2020-12-29 15:28

    Once you've used Python's json or simplejson module to load the JSON data into Python objects, everything should just work in your template.

    Before sending things to your template I would pull out the results like so...

    def foo_view(request):
        ....
        decoded_json = json.loads(json_string)
        return render_to_response('foo.html',{'results':decoded_json['Result']})
    

    That way in your template you'll be able to work on each result like so...

    <ul id="results">
         {% for result in results %}
         <li>Result{{ forloop.counter }}: {{ result.URL }}, {{ result.PlaylistID }}, {{ result.Name }} ...</li>
         {% endfor %}
    </ul>
    

    The data in the output will appear in the same order as it did in the JSON array at Results. If you need to sort the data then you will need to do that in your view, NOT in your template.

    0 讨论(0)
提交回复
热议问题