Javascript/jQuery function to replace values inside json file
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I need a javascript or jQuery function to loop through a json file and replace multiple values inside with other values.

For example I want to replace these two values below:

    "brand": "Tory Burch",
    "currency": "Tory Burch",

With

    "brand": "New Brand",
    "currency": "GBP",

The demo json file is here:
http://pastebin.com/wPH68SLi

I'm going to use this script inside a third party API and you should make sure that it will work, here's two simple docs you can quickly take a look :)

https://help.kimonolabs.com/hc/en-us/articles/203744354-Modify-your-API-results-with-a-javascript-function

https://help.kimonolabs.com/hc/en-us/articles/204088270-Examples-Modify-Results-Function

Is this going to be run inside of a browser?
slang800 almost 4 years ago
Yea inside a browser, it should be just a regular javascript function
user0809 almost 4 years ago
Hi, the values to be replaced, will they be the same values for all the items ? or will they be different ?
vmark99 almost 4 years ago
The values will be the same for this file. For example this is file 1 then the values will be same. If this file is file 2 then the values will be different. The function should accept several parameters
user0809 almost 4 years ago
awarded to tomtoump

Crowdsource coding tasks.

2 Solutions

Winning solution

This works as the example you provided.

function(data) {
  for(var collection in data.results) {
    data.results[collection].forEach(function(row) {
      if (row.brand == "Tory Burch") {
        row.brand = "New Brand";
      };
      if (row.currency == "Tory Burch") {
        row.currency = "GBP";
      };
    });
  };
  return data;
}

I believe something like this will do for your case:

function(data, brand, currency) {
  for (var collection in data.results) {
    data.results[collection].forEach(function(row) {
      row.brand = brand;
      row.currency = currency;
    });
  }
  return data;
}

The 'brand' and 'currency' parameters are the corresponding values you want to change to.

Here is a pastebin of your example file changed http://pastebin.com/JjQQUq75.

Let me know if I can change something.

View Timeline