I am trying to learn how to save in Django part of a json content coming from a kraken api. Going through several examples here on stackoverflow i came up with this code:
views.py
from django.shortcuts import render
from meal_app.models import Kraken
import requests
def get_krakens(request):
all_krakens = {}
url ='https://api.kraken.com/0/public/Assets'
response = requests.get(url)
data = response.json()
for i in data:
kraken_data = Kraken(
name = i['altname']
)
kraken_data.save()
all_krakens = Kraken.objects.all().order_by('-id')
return render (request, 'krakens/kraken.html', { "all_krakens":
all_krakens} )
How can i solve this error? My json is visible in my console but i cannot access the value 'altname'. Your help would be really appreciated.
/Users/davidmoreira/Documents/crypto/djangokrakenapi/meal_project/meal_app/views.py, line 14, in get_krakens
name = i['altname']
CodePudding user response:
On iPad so can’t check but I suspect your ‘i’ is a string and will need to be converted to a Python object/dictionary before you can extract the sub element from it.
Look at the json.loads
method in the json
module.
CodePudding user response:
Your "i" is in the form of a string. You need to convert it to an object first.
Using i = json.loads(i)