Forums

How to sort out/tidy up mega dictionary response from API?

How to separate out the values from this api response dictionary?

'{"event":[{"idEvent":"508788","idSoccerXML":"364310","strEvent":
"Arsenal vs Chelsea","strEventAlternate":"Chelsea @ Arsenal","strFilename":
"English Premier League 2016-09-24 Arsenal vs Chelsea","strSport":"Soccer","idLeague":"4328","strLeague":"English Premier League","strSeason":"1617","strDescriptionEN":null,"strHomeTeam":"Arsenal"
,"strAwayTeam":"Chelsea","intHomeScore":"3","intRound":"6","intAwayScore":"0","intSpectators":"0","b":"unlocked"}]}'

I need it to show the scores:

ie. Arsenal 3 Chelsea 0

but can't get it to separate out the values - any ideas?

actually, no worries, I have this worked out now

print("Team {0} has a score of {1}".format(d["results"][0]

    ['strHomeTeam'],d["results"][0]['intHomeScore']))

    print("Team {0} has a score of {1}".format(d["results"][0]

    ['strAwayTeam'], d["results"][0]['intAwayScore']))

I'll come back later if anyone is good at this stuff, as the dictionary is long and there are more scores that need digging out

by the way , how to tidy up the display?

https://madmartin.pythonanywhere.com/sport

renders as: ('Coventry', '1') ('Lincoln', '0')

looks kind of messy...

Use however you're generating the html for the page to separate the values so you can format them nicely.

I've tried a whole variety of trying to get rid of the apostrophes, such as: (in sport.html)

 <br>
    {{ x }}<br>
     {{ x|striptags|title }}<br>

     {{ x|e }}<br>

     {{ x|pprint|title }}<br>

however, still end up with : ('Coventry', '1') ('Lincoln', '0')

is there an easy way to just get rid of the ' and () : ?

You need to address each of the variables individually in your template. Now it looks like you are combining them.

what I need is for this:

d2 = d["event"][0]['strHomeTeam'],d["event"][0]['intHomeScore']
    for i in range(2,len(d2)-6):
        print( "".join(d2[i]),end="")

to print out: Coventry: 1

in the url - this works fine in Python idle, but can't convert it to variable in flask

something along the lines of this would be handy:

def scores(x):

    for i in range(2,len(d2)-5):
       g =  print( "".join(d2[i]),end="")  
         return g

 render_template('sport.html', g=g)

this doesn't work though, so how to convert the 'print' section here into a usable variable?

The print function writes output to the console (which, in a website's code, means "to the server log") and returns the value None. If you want to provide your template with the stuff that your first code example is printing, then something like this would do the job:

d2 = d["event"][0]['strHomeTeam'],d["event"][0]['intHomeScore']
g = ""
for i in range(2,len(d2)-6):
    g = g + "".join(d2[i])
render_template('sport.html', g=g)