Home Ask Login Register

Developers Planet

Your answer is one click away!

user1733735 February 2016

How to change each value in a JSON in python

output = {'name': 'StackOverflow',
  'competitors': [{'competitor': 'bing',
                   'link': 'bing.com'},
                  {'competitor': 'google',
                   'link': 'google.com'}],
  'acquisition': {'acquired_day': 16,
                  'acquired_month': 12,
                  'acquired_year': 2013,
                  'acquiring_company': {'name': 'Viggle',
                                        'permalink': 'viggle'}}}

I have code which looks like this:

def traverse(obj):
    if isinstance(obj, dict):
        for key, value in obj.iteritems():
            print('dict_key', key)
    elif isinstance(obj, list):
        for value in obj:
        print('value', obj)


This code traverses the whole JSON and prints each value and key. I need to set each value to a random string


g.d.d.c February 2016

If you pass along a reference to the parent and a location with your values you can make the modifications in place:

def mangle(obj, parent = None, key = None):
    if isinstance(obj, dict):
        for key, value in obj.iteritems():
            mangle(value, obj, key)
    elif isinstance(obj, list):
        for idx, value in enumerate(obj):
            mangle(value, obj, idx)
        parent[key] = 'nonsense'


>>> pprint(output)
{'acquisition': {'acquired_day': 'nonsense',
                 'acquired_month': 'nonsense',
                 'acquired_year': 'nonsense',
                 'acquiring_company': {'name': 'nonsense',
                                       'permalink': 'nonsense'}},
 'competitors': [{'competitor': 'nonsense', 'link': 'nonsense'},
                 {'competitor': 'nonsense', 'link': 'nonsense'}],
 'name': 'nonsense'}

Post Status

Asked in February 2016
Viewed 2,706 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life