Recursively traverse json and trim strings in Python

Question:

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

Asked By: sadat

||

Answers:

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)
Answered By: tdelaney
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.