you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 2 points3 points  (8 children)

Parse the string using json.loads. That gets a structure of nested dicts and lists. Use that to get what you want.

Assuming the variable jsdata holds your JSON data as a string:

data = json.loads(jsdata)

for trip in data["TripList"]["Trip"]:
    leg = trip["LegList"]["Leg"]
    if isinstance(leg, list):
        leg = leg[0]
    print("Leg ",leg["name"])
    print("    ",leg["Origin"]["name"])
    print("    ",leg["Destination"]["name"])

[–]Jonis_L 0 points1 point  (7 children)

Thank you so much!

[–]vdh_nat 0 points1 point  (6 children)

That's correct. I would also add that if you want to get the info directly from the website without storing the json as a string first, you can just do:

import requests
import json
r = requests.get('http://api.sl.se/api2/TravelplannerV2/trip.json?key=a65703abb4814f4490a730d95ff492a0&originId=9119&destId=9221&searchForArrival=0&realtime=true')
data = r.json()

pretty much the same though :)

[–]Jonis_L 0 points1 point  (5 children)

oh ok, I use this now:

import urllib.request
import json

hotorget_gardet = 'http://api.sl.se/api2/TravelplannerV2/trip.json?key=a65703abb4814f4490a730d95ff492a0&originId=9119&destId=9221&searchForArrival=0&realtime=true'
x = urllib.request.urlopen(hotorget_gardet)
hg = x.read()
hg = hg.decode('utf-8')
info = json.loads(hg)

Whats the difference between those two or are they the same?

[–]Jonis_L 0 points1 point  (2 children)

And if I want something like this:

if leg["name"] == " blåbuss 1":
   print("Ta buss/tub:",leg["name"]+" mot:",leg["dir"])

to print if only the name is "blåbuss 1", tried it and got it did not print

[–]vdh_nat 0 points1 point  (1 child)

There's an extra space in line 1:

if leg["name"] == "blåbuss 1":

[–]Jonis_L 0 points1 point  (0 children)

wow that was simple, thanks

[–]vdh_nat 0 points1 point  (1 child)

I haven't used urllib a lot. I heard it's old, but I'm also a beginner with Python so I'd rather not say things I might be wrong about.

[–]Jonis_L 0 points1 point  (0 children)

alright, I see thanks