0

I am new to python or JSON. I do a request to an API, can reach the data and print all the data that I need. The problem is : I print only one element, i would like to print all the loop.

import json
from urllib.request import urlopen

with urlopen("myapiurl") as response: source = response.read()

data = json.loads(source)


for item in data ["resultsPage"]["results"]["calendarEntry"]:
    artistname = item["event"]["displayName"]
    hour = item["event"]["start"]["time"]
    day = item["event"]["start"]["date"]
    oid = item["event"]["id"]
    venue = item["event"]["venue"]["displayName"]
    newJson = (
     {oid:{
      'artist': artistname,
      'hour': hour,
      'day': day,
      'location': venue,
      'description': "",
      'expires': 1,}
     })

    with open('concert.json', 'w') as json_file:
        json.dump(newJson, json_file, sort_keys=True, indent=2)

Let me know if you need the api url. Thanks !

4
  • Can you fix the indentation after the for loop? If the writing of the file happens outside the loop then you will only be writing one file. If you are doing multiple opens, writes, closes to the same file then it should be opened in append mode ('a' instead of 'w'). Commented Aug 7, 2019 at 17:14
  • I changed 'w' to 'a' but now the last item of the loop is print two times. Could you explain the first part of your answer ? Thanks Commented Aug 7, 2019 at 17:24
  • In the code you posted, there is no indentation after you begin the for loop. There is also no indentation after the with statement at the bottom. As it is, this code won't even run and will raise an IndentationError. In other words, it's hard to see where your for loop ends. Commented Aug 7, 2019 at 17:49
  • i updated my post, hope you can help Commented Aug 7, 2019 at 17:59

1 Answer 1

1

I would suggest you to try this with opening and closing file only once.

import json
from urllib.request import urlopen

with urlopen("myapiurl") as response: source = response.read()

data = json.loads(source)

newJsonx=dict()
for item in data ["resultsPage"]["results"]["calendarEntry"]:
    artistname = item["event"]["displayName"]
    hour = item["event"]["start"]["time"]
    day = item["event"]["start"]["date"]
    oid = item["event"]["id"]
    venue = item["event"]["venue"]["displayName"]

    newJson = (

     {oid:{
      'artist': artistname,
      'hour': hour,
      'day': day,
      'location': venue,
      'description': "",
      'expires': 1,
     }
     })
    newJsonx.update(newJson)



with open('concert.json', 'w') as json_file:
    json.dump(newJsonx, json_file, sort_keys=True, indent=2)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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