Python - replace unknown key value in json

I am new to Python, so here is my question.

I am making an HTTP request to retrieve some JSON data that was created using Javascript. This JSON can have some meanings, such as "nan", "inf"or "-inf"as strings. The keys and depth of these values ​​are unknown. What I want to do on the Python side is to find these values ​​and replace them with the Python equivalent float("nan")or float("inf").

Changing anything on the Javascript side is out of the question, as I was told.

I use the following function to read an HTTP response and return the JSON equivalent

def http_response_to_json(response):
    response_str = ""
    CHUNK = 16 * 1024

    while True:
        try:
            chunk = response.read(CHUNK)
            if not chunk:
                break
            response_str += chunk
        except httplib.IncompleteRead, e:
            response_str += e.partial

    return json.loads(response_str)

I read the parameter object_hook json.loads, but I'm not sure what and how I can use it.

PS I am using Python 2 yet

thanks

+4
1

JSON.loads . , .

def cleanup(dirty_data):
    if isinstance(dirty_data, dict):
        for key in dirty_data:
            value = dirty_data[key]
            dirty_data[key] = cleanup(value)
        return dirty_data
    elif isinstance(dirty_data, str):
        if dirty_data in ["nan", "inf", "-inf"]:
            return float(dirty_data)
    else:
        return dirty_data

test_object = {"test": 123, "a": {"b": "nan"}}

print(cleanup(test_object))

: {'a': {'b': nan}, 'test': 123}


EDIT: , Python 2.

def cleanup(dirty_data):
    if isinstance(dirty_data, dict):
        for key in dirty_data:
            value = dirty_data[key]
            dirty_data[key] = cleanup(value)
        return dirty_data
    elif isinstance(dirty_data, str) or isinstance(dirty_data, unicode):
        if dirty_data in ["nan", "inf", "-inf"]:
            return float(dirty_data)
    else:
        return dirty_data

test_object = {"test": 123, "a": {"b": "nan"}}

print(cleanup(test_object))
+1

Source: https://habr.com/ru/post/1625084/


All Articles