Dealing with json null in python

Viewed 31

I am trying to get some data from a trading API in the web. The data are returned in a JSON format as shown below and my program is written in python:

{ "result": [ {
        "name": "ALGOBEAR/USD",
        "enabled": true,
        "postOnly": false,
        "priceIncrement": 1e-08,
        "sizeIncrement": 1000000000000.0,
        "minProvideSize": 1000000000000.0,
        "last": 1e-08,
        "bid": null,
        "ask": null,
        "price": null,
        "type": "spot",
        "futureType": null,
        "baseCurrency": "ALGOBEAR",
        "isEtfMarket": true,
        "quoteCurrency": "USD",
        "underlying": null,
        "restricted": false,
        "highLeverageFeeExempt": true,
        "largeOrderThreshold": 350.0,
        "change1h": 0.0,
        "change24h": 0.0,
        "changeBod": 0.0,
        "quoteVolume24h": 0.0,
        "volumeUsd24h": 0.0,
        "priceHigh24h": 0.0,
        "priceLow24h": 0.0
    }]}

In this list there are over 500 of similar dictionaries as the above. The problem is that the null values that are returned e.g. "price": null cannot be compared with the float values of prices(if they are equal, bigger or smaller) of other dictionaries e.g "price": 0.00019845 and the program returns an error.

I would like to ask if there is a way to deal with these null values so that the python programme can identify them. For example if there is a way to transform them into None so that python can deal with them or delete the dictionaries in the list above that contain null values from the beginning using maybe a json method.

Thanks!

1 Answers

The null values become None automatically when loaded using the json module in the Python standard library.

import json
content = '["foo", {"bar":["baz", null, 1.0, 2]}]'
data = json.loads(content)
print(data)
# ['foo', {'bar': ['baz', None, 1.0, 2]}]

See official docs.

Related