Luciano Nascimento
Luciano Nascimento

Reputation: 2600

Python Loop JSON API Request

I'm trying to make a script that runs an infinite function in python to read a JSON API, but from the second loop it returns an error.

I think it's very simple, but I'm not familiar with Python and I did not find the answer on the internet.

Code:

#! /usr/bin/python3

import urllib.request
import json
import time

while True:
    request = urllib.request.urlopen("https://jsonplaceholder.typicode.com/todos/1").read()

    json = json.loads(request.decode('utf-8'))
    print("JSON: ", json)

    time.sleep(1);

Output:

JSON {'id': 1, 'completed': False, 'title': 'delectus aut autem', 'userId': 1}
Traceback (most recent call last):
  File "./test.py", line 25, in <module>
    json = json.loads(request.decode('utf-8'))
AttributeError: 'dict' object has no attribute 'loads'

Upvotes: 0

Views: 203

Answers (2)

Raviteja Ainampudi
Raviteja Ainampudi

Reputation: 282

I believe this is name convention issue with json. Try this.

import urllib.request
import json
import time

while True:
    request = urllib.request.urlopen("https://jsonplaceholder.typicode.com/todos/1").read()
    json_1 = json.loads(request.decode('utf-8'))
    print("JSON: ", json_1)
    time.sleep(1);

Upvotes: 1

abc
abc

Reputation: 11929

You are changing json from referring to the json module to be a variable at the line

json = json.loads(request.decode('utf-8'))

This is why it only works for the first iteration.
Thus, you only need to change the name to something different.

Upvotes: 1

Related Questions