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)
            traverse(value)
    elif isinstance(obj, list):
        for value in obj:
            traverse(value)
    else:
        print('value', obj)


traverse(output)

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

Answers


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)
    else:
        parent[key] = 'nonsense'


mangle(output)

>>> 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

Search




Leave an answer