Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Recursively traverse json and trim strings in Python

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,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading