3👍
To iterate, you need it to be a python dict
object and not the JSON string.
You can do it using the json
package.
Example:
import json
string_containing_json = ".."
data = json.loads(string_containing_json)
Json is just a string arranged in special format. You need to convert it to python objects before using it.
EDIT: I have no idea why the downvote. Judging from the question, this is definitely the issue here. The OP is not converting the json string into dictionary. You can’t iterate over a string, like you do a dictionary.
2👍
You should not dump the data back to JSON in the view. Once you’ve done that, it’s now a string, so it doesn’t have an items
method.
You should pass the result of response.json()
directly to the template.
- [Django]-How to filter objects by price range in Django?
- [Django]-How to set default value in Django while filtering objects from models
- [Django]-@detail_route does not work pagination in django rest framework
1👍
I think, within the view, you need to convert the response
like this:
import json
response = requests.request("GET", url, data=payload, headers=headers, params=querystring)
json_string = json.dumps(response)
return render(request,'searchhome.html',{'dataset':json_string})
And then, I think, you can access the data as
{{ dataset.response_code }}
{{ dataset.response.0 }}
etc
- [Django]-Trying to test django app locally with foreman
- [Django]-How to make form labels and fields display on the same line in django-crispy-form
- [Django]-Django Form Field to support US or International phone numbers?
- [Django]-TypeError: 'RegexValidator' object is not iterable
- [Django]-__init__() missing 1 required positional argument: 'model_field'
1👍
Finally I could solve it.
My changed view:
response = requests.request("GET", url, data=payload, headers=headers, params=querystring)
response = json.loads(response.content)
json_string = response["response"]
return render(request,'searchhome.html',{'dataset':json_string})
My Template
{% for k,v in dataset.items %}
<tr>
<td>
{{k}}:{{v}}</td>
<tr>
{% endfor %}
Solution came with trying all answers posted and just adding .content
to json.loads(response)
- [Django]-How to display the last login date and time on the users list on the django admin site?
- [Django]-Django Rest Serializer returns empty
- [Django]-Elasticsearch:Unknown command: 'search_index'
- [Django]-Feature differentiation: Rails / Django