Traverse through JSON to find and replace a value

This small code snippet helps you to traverse through JSON Object and replace a particular value.


function findAndReplaceValueforKeyInJson(object, value, replacevalue, targetKey) {
        //key must not be null
        if (targetKey !== null && targetKey !== '') {
                //split the given key using '.' which will help us to traverse through JSON object
                var keys = targetKey.split('.');
                //loop through JSON Object
                for (var x in object) {
                        //check for key matches
                        if (keys.indexOf(x) !== -1) {
                        //check whether matched key-value is an object or not, if object again call the same function to repeat the process
                                if (typeof object[x] === typeof {}) {
                                        findAndReplaceValueforKeyInJson(object[x], value, replacevalue, targetKey);
                                }
                                // if not object replace with new value & come out of for loop
                                if (object[x] === value) {
                                        object[x] = replacevalue;
                                        break;
                                }
                        }
                }
        }
}

Hope this helps..

Advertisements

One thought on “Traverse through JSON to find and replace a value

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s