Handling KeyError: key “nameOfKey” not found

I have a script that looks through a JSON structure. Every now and again, a particular key is missing. When these instances occur, I need the script to continue rather than stop. Here is my code:

for i = 1:length(marketCatalogueResult)
        marketResults = getMarketOffers(currentCatalogue[i,1])
        push!(lastTradeP1, marketResults[1]["runners"][1]["lastPriceTraded"])
        push!(lastTradeP2, marketResults[1]["runners"][2]["lastPriceTraded"])
    end
end

The error I sometimes get is:

KeyError: key "lastPriceTraded" not found

How can I amend my code to handle the stated error?

What do you want the code to do in the case when the key doesn’t exist?

3 Likes

Insert NaN

You can use the get function to get either the value associated with a key or some default if that key does not exist. For example:

julia> results = Dict("lastPrice" => 1.0, "currentPrice" => 2.0)
Dict{String,Float64} with 2 entries:
  "currentPrice" => 2.0
  "lastPrice"    => 1.0

julia> get(results, "lastPrice", NaN)
1.0

julia> get(results, "futurePrice", NaN)
NaN

Try running ?get for more information.

4 Likes

You may want to consider using missing instead, which is the Julian way to indicate missing data. NaN has a very specific meaning, which is that it is the result of a computation where zero was divided by zero or infinity was subtracted from itself.

4 Likes

While I agree with the semantics, the temptation of just keeping things simple with a single primitive type, with no unions or risk of type instability should not be underestimated. I have some data wrangling code that deal with Float64 columns that will never have a “true” NaN (things like X_time where X is a procedure that is not always called) so it is very useful to just use NaNs as a sentinel value.

Good point. NaN is also a good choice here.

1 Like

When I attempt to implement that solution, I get an error to do with float:

Anything obvious I am doing wrong?

It seems marketResults is an Array{Any, 1}, not a Dict?

1 Like

Looks like you need something like this:

get(marketResults[1]["runners"][1], "lastPriceTraded", NaN)

You can’t do the indexing and then call get, you replace the indexing with the call to get.

2 Likes