Home > Enterprise >  Recursively traverse json and trim strings in Python
Recursively traverse json and trim strings in Python

Time:12-12

I have a json like which has extra spaces

{"main": "test   ","title": {"title":  "something. ","textColor": "Dark"},"background": {"color":  "White  "}}

I want to make a new json by removing the extra spaces

{"main": "test","title": {"title":  "something","textColor": "Dark"},"background": {"color":  "White"}}

So far I got is which can print each key and values,

def trim_json_strings(json):
    for k, v in json.items():
        if isinstance(v, dict):
            trim_json_strings(v)
        else:
            strippedValue = v.strip() if isinstance(v, str) else v
            print(k.strip(), strippedValue, end = '\n')

Not an expert in Python. Thanks in Advance

CodePudding user response:

You are close. Just reassign the stripped value back to the dictionary you are iterating. Changing the thing you are iterating can be dangerous, but in this case where you are just updating values for existing keys, you'll be okay. This will be an in-place change, so the original dict structure will be fixed.

def trim_json_strings(json):
    for k, v in json.items():
        if isinstance(v, dict):
            trim_json_strings(v)
        else:
            if isinstance(v, str):
                json[k] = v.strip()

            
data = {"main": "test   ","title": {"title":  "something. ","textColor": "Dark"},"background": {"color":  "White  "}}

trim_json_strings(data)
print(data)
  • Related