I need help with with json and lists

Hi everyone, I hope you hare having great day. I have a question about Python.

I have a function that converts the strings from camel to snake. I want to use it for every key in the response I get. How can I do it?

def camel_to_snake(name):
    ----function is here.----

req = requests.get(url, json=None, headers=headers, params=params))

#example response:
    "listOfSomething": [
            "key1": "value",
            "key2": "value",
            "key3": "value",
            "key4": "value",
            "key5": "value",
            "key6": "value"

Since JSON objects are passed as strings, you can literally just call the method replace. As here:

I’m going to assume by your example that you already have the response converted to Python datatypes (responses returned by requests have a .json() method to try if not).

Python dictionaries have a .items() method that returns an iterator of key-value pairs in a dictionary that works well for purposes such as this.

new_dictionary = {}
for key, value in old_dictionary.items():
    new_key = camel_to_snake(key)
    new_dictionary[new_key] = value

Or, more concisely using comprehensions

new_dictionary = {camel_to_snake(key): value for key, value in old_dictionary.items()}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.