0

I have a JSON object in string that looks like '{"key1":"value1", "key2": "value2", "key3": "value3"}'

I can use json.loads to make that into a JSON object, but when I try to print it in HTML, it prints the entire JSON object like

{"key1":"value1", "key2": "value2", "key3": "value3"}

my function looks like:

def jsonPretty(json_string):
    return json.loads(json_string)

and in HTML/Django:

{{kvpair|jsonLoadsPretty}}

However I want it to print

key1 value1 key2 value2 key3 value3

The format can vary a little, but I want each key-value pair to separate by a \n, and the brackets should be removed.

What would be the best way of doing this?

EDIT:

I'm using {% with kvpair|jsonPretty as kvjson %} before running a for loop with

{% for k, v in kvjson.items %}
    <p> {{k}} {{v}}</p>

and now it works fine. Thanks for @Andrey Shipilov 's help!

2 Answers 2

2
{% for key, value in kvpair %}
    <p>{{ key }} {{ value }}</p>
{% endfor%}

https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#for

Sign up to request clarification or add additional context in comments.

5 Comments

the kvpair is a string, so I tried json.loads first before using that for loop. However it returns error: TemplateSyntaxError: Could not parse some characters: |{{kvpair||jsonLoadsPretty}}
Make a JSON object from your string and then pass it to the template. Then you'll be able to do {% for %} on it.
I am using the jsonPretty function written above. My line in HTML now looks like {% for k, v in kvpair|jsonPretty %}. If i just output k, it gives me the keys, but outputting k,v somehow makes it a string again and returns the first 2 characters of the key.....
Try {% for key, value in kvpair.items %}
I set the result of that function to a variable first and the for loop worked. Thanks!
0

works {% for key, value in kvpair.items %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.