Using type hints for a JSON object in Python

Is there a way to specify type hints for JSON objects with an unknown or changing structure? I want to avoid using Any or methods like cast() as much as possible.

I think the correct hint would be:

Json: TypeAlias = dict[str, "Json"] | list["Json"] | str | int | float | bool | None

Issue

However, this hint seems to not always work. The issue is illustrated below in a code sample.

import requests
from typing_extensions import TypeAlias

Json: TypeAlias = dict[str, "Json"] | list["Json"] | str | int | float | bool | None

res: requests.models.Response = requests.get(
    "https://randomuser.me/api/?results=5&nat=gb"
)

data: Json = res.json()

results: Json = data["results"]

When trying to access data["results:"], errors are generated by mypy as shown below:

No overload variant of "getitem" of "list" matches argument type "str" [call-overload]

Possible overload variants: def getitem(self, SupportsIndex, /) -> Json def getitem(self, slice, /) -> list[Json]

Value of type "dict[str, Json] | list[Json] | str | int | float | bool | None" is not indexable [index]

Inquiry

What mistake am I making here? I came across this GitHub thread which might have the solution, but I may not yet fully understand types to implement it correctly.

Thank you!

Answer №1

Every string can be considered a suitable instance of JSON. Therefore, if you try to access an element within a JSON object using indexing like data["result"], the static type checking tool may indicate an error as it is not a valid operation on a string. To resolve this, you should define the variable as

data: dict[str, JSON] = result.json()
. Alternatively, it is advisable to use a Typed Dictionary specifying the complete structure of the document.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

use a map function that takes in two integers and apply it to a list containing multiple lists

I am attempting to apply the map function to the triangle_area formula by using each 2 integer pairs from this list of lists. However, I keep getting an error that says I am missing one of the required variables "h". # map function def area_triangle(b,h): ...

Determine the total amount of pages generated from the Twitter search API

Can the Twitter search API provide a count of the pages returned? I'm curious if there is a method to determine how many pages are available for a particular query. ...

Executing an authenticated Guzzle POST request

Just starting out with guzzle and I need help on how to make a Guzzle call for this specific request. curl -X POST -u username:password -H "Content-Type: application/json" https://xyz/api/v1/accounts.json -d '{"user":{"username":"test","password":"xy ...

Display a blank response using Dailymotion's PHP API json echo functionality

After extensively utilizing the Dailymotion json API with PHP references, I encountered an issue. When simply accessing the api url through a web browser, I could easily copy and use the "stream_h264_url" content for playback. However, when attempting to o ...

Custom Jackson Deserialization to Map String Class Names to Class Definitions

Utilizing custom Jackson Deserializers for parsing a JSON file is my current task. Within this JSON file, there are numerous entries with the key "class" and values representing the class names (without the full package name). The deserializer has access t ...

Creating and utilizing JSON data in the KAFKA platform

We have decided to integrate Apache Kafka 2.10 into our project and facilitate communication using JSON objects between the producer and consumer modules. In order to achieve this successfully, I believe it is essential to: Create a custom serializer to ...

What sets apart an Op from a Function in programming?

Theano features Ops and functions. What sets them apart? Defining functions is straightforward, for example: x = T.dmatrix('x') linmax = function([x], T.maximum(x,0)) Ops on the other hand, can be more intricate to create. They involve abstr ...

Guide on parsing and totaling a string of numbers separated by commas

I am facing an issue with reading data from a JSON file. Here is the code snippet from my controller: myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { console.log('abc ...

Transforming JSON data into a Model-View-Controller

Although I have searched for answers to similar questions, the solutions I found do not seem to work in my case. I am attempting to pass JSON data to an MVC controller, but the controller is never being called. Any suggestions? Here is the Ajax call: fun ...

Create a Python function that takes a list as input, iterates through each element, converts it to

When working with a Python list that requires double quotes around the strings in order to pass it to an API as a list of double quote strings, I encountered an issue. The data needed by the API: data = { "styles" : styleList } It worked when I manu ...

Creating a basic JSON array using the push method

When adding comments to a blog post using the line: blogpost.comments.push({ username: "fred", comment: "Great"}); The JSON structure of the comments section will look like this: "comments":[{"0":{"username":"jim","comment":"Good",},"1":{"username":"fre ...

Linux and selenium combine forces to kickstart traffic implementation

I have written a Python script using Selenium and I am looking to implement the following functionality (pseudo code) open www.example.com while traffic usage has not been 0 in the last 3 seconds: wait 3 seconds print "everything is loaded" Selen ...

How to create a JsonPath query in C# using Newtonsoft Json.NET for a null property

Suppose we have a JSON array containing: [ { "id": 1, "name": "abc" }, { "id": 2 }, { "id": 3, "name": "def" } ] In this scenario, if we use th ...

Having trouble accessing a URL using Selenium in Python, but the browser opens without any issues

from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.keys import Keys import time import datetime ch_options = webdriver.ChromeOptions() ch_options.add_argument("--user-data-dir=C:\ ...

Is leveraging the conda-forge channel with Anaconda causing issues in the overall setup?

Lately, I've encountered some difficulties while using the navigator and Conda for module installations and updates. Upon doing some research, I discovered that adding or removing channels can help resolve certain issues. For instance, when I tried ru ...

Error: The command SEARCH is not permissible in the AUTH state; it can only be executed in the SELECTED states in python when using imaplib

**Here is the code I wrote to access and search the trash folder of emails using the imap4 library.** def trash(request): global i, addr, passwrd, conn if request.method == 'POST': imap_url = 'imap.gmail.com' co ...

Flask is throwing an sqlalchemy exception with the error: psycopg2 is reporting an UndefinedColumn for a column

I am currently facing an issue while trying to run raw SQL queries on my Python application with a Heroku database. I have already set up the tables by running a separate script. Check out the model here My database configuration looks like this: engine ...

What are the steps to communicate with multiple PDFs containing varied information using langchain?

After successfully creating a web interface for chat with a single PDF document using langchain, OpenAI, and Pinecone, I encountered a challenge when trying to incorporate new documents into the vector store. The information from the additional documents d ...

The error message "Data type must be consistent across all series on a single axis in Google Chart" may cause confusion

I'm struggling with an error message that appears when I try to run my Google chart. Here is the code I am using to generate the chart. function (resultVal) { var arrMain = new Array();//[]; for (var i = 0; i < resultVal.length; i++) { ...

Disabling grid propagation in tkinter

Trying to create a Frame using the grid manager, with Label widgets inside. The goal is for the label widget to fill the frame it's in, but instead the frame keeps resizing itself based on the label. Attempted to use grid_propagate(False) method, but ...