Read and Parse a JSON File From a URL in Python

Reading JSON from a URL in Python turns a remote response into data you can work with immediately. Fetch the response with urllib.request, then pass its body to json.loads to get a dictionary or list. This pattern fits public APIs, hosted configuration files, and datasets that change independently of your code.

Python Read JSON From URL Example

Output:

Output will appear here...

Output:

Squad: Super Hero Squad
Members: 3

How This Example Works

  1. urllib.request.urlopen(url) sends a synchronous GET and returns an HTTP response; the with block closes the connection afterward.
  2. response.read() returns the body as raw bytes. json.loads accepts bytes directly, so no manual .decode("utf-8") step is needed.
  3. Parsing turns the JSON object into a Python dict, which you index with data["squadName"] and measure with len(data["members"]).

In this runtime urlopen is synchronous, so it takes no await and no asyncio even though many tutorials wrap network calls in async code.

json.load vs json.loads

Both deserialize JSON into Python objects; they differ in what they read from.

FunctionInputUse it when
json.loads(...)a str or bytes valueyou already hold the content, such as response.read()
json.load(...)a file or stream objectyou have an open handle, such as open(path) or the response itself

Here json.loads(response.read()) and json.load(response) produce the same dict. Passing the wrong type is the usual error: feeding a string to json.load or a file object to json.loads raises AttributeError or TypeError.

Inspect the JSON Request in Run Details

Open Run Details after the program finishes. It separates the network request the script made from the packages the runtime loaded to execute it.

Run Details signalWhat it means
Requests shows one GET to raw.githubusercontent.com with status 200The JSON file was fetched over the network successfully
The request duration in msHow long the fetch itself took, separate from parsing
The request is 403/404, blocked, or failedThe URL was unreachable or not CORS-enabled, so it never reached your code
Packages is empty (“No runtime packages”)json and urllib are standard library, so nothing was installed

That empty Packages section is the giveaway that this approach is install-free. Examples that import beautifulsoup4 or pandas list a loaded package here, such as the web scraping example; reading JSON with the standard library lists none.

Reading from a URL works in the browser only when the endpoint sends CORS headers. The fixture above is a CORS-enabled file on GitHub raw; a cross-origin URL without those headers is blocked before your code runs, which surfaces as a failed request rather than a JSONDecodeError.

Common Mistakes When Reading JSON From a URL

Mistake: reading the response stream twice.

Wrong:

raw = response.read()
data = json.loads(response.read())

Right:

data = json.loads(response.read())

Why it happens: urlopen returns a stream you consume once; a second read() returns empty bytes.

Mistake: calling .get() on a parsed JSON array.

Wrong:

data = json.loads(response.read())
first = data.get("name")

Right:

data = json.loads(response.read())
first = data[0] if isinstance(data, list) else data["name"]

Why it happens: a top-level JSON array parses into a Python list, which has no .get; index it instead.

Handling Errors and Missing Keys

urlopen raises HTTPError for 4xx and 5xx responses, but the error object is still readable, so a JSON error body can be parsed by catching it with try/except:

from urllib.error import HTTPError

try:
    with urllib.request.urlopen(url) as response:
        data = json.loads(response.read())
except HTTPError as err:
    data = json.loads(err.read())

For an optional field, use data.get("key") to return None instead of raising KeyError. The standard library json module parses untrusted input safely, so never use eval() to read JSON.

FAQ

How do you read a JSON file in Python?

For a remote file, open it with urllib.request.urlopen(url) and pass the bytes to json.loads. For a file on disk, use with open(path) as f: data = json.load(f). Both return a Python dict or list.

What is the difference between json.load and json.loads?

json.load reads from a file or stream object, while json.loads reads from a str or bytes value. The trailing “s” stands for string. Use loads when you already hold the content in memory.

Do you need the requests library to read JSON in Python?

No. urllib.request and json are both standard library, so you can fetch and parse JSON with zero installs. The requests library adds conveniences like a .json() helper and session handling, but it is a third-party dependency.

What is JSON in Python?

JSON is a text format for structured data. Python maps a JSON object to a dict, an array to a list, and the primitives to str, int, float, bool, and None, which is what json.loads returns after parsing.