I'm trying to construct a function which will replace the value based on the path user given as input argument. I have a complex JSON with some duplicated key and user will give path of the element and based on that path It needs to replace the value of the particular key (which is possibly duplicated):
SampleJSON.json:
{
"product": "delivery",
"Merchant": {
"payment_method": "GPay"
},
"transactions": [
{
"amount": {
"total": "100",
"currency": "USD",
"details": {
"subtotal": "100",
"tax": "1",
"insurance": "0.1"
}
},
"description": "The payment transaction description",
"custom": "JACKSON DISPUTERS SYSTEMS",
"invoicenumber": "",
"descriptor": "null",
"itemlist": {
"items": [
{
"name": "COMPUTER",
"description": "BLACK",
"quantity": "1",
"price": "100",
"tax": "1",
"currency": "USD"
}
],
"shippingaddress": {
"recipient_name": "JACKSON DISPUTERS SYSTEMS",
"line1": "XXXX",
"line2": "XXXX",
"city": "XXXX",
"country_code": "XX",
"postal_code": "XXXX",
"phone": "XXXXXX",
"state": "XXXXXX"
}
}
}
],
"note_to_payer": "Contact us for any questions on your order."
}
User Input:
arg1: product.transactions.currency,
arg2: EUR
I just need to traverse through the above path (arg1) and replace the value of currency as AUD (arg2).
If you noticed the currency element is available in two different places in the given JSON file but I just want to replace the currency which is under the transactions array that mentioned in the arg1, and not the other one.
I just created the below code so far and It will traverse through each and every element in the given JSON but not sure how to replace the value for the given key (arg1).
const arg1 = "product.transactions.currency";
const condition = arg1.toString().split(".");
const arg2 = "EUR";
const cond = false;
function process(key,value) {
if(key === condition[condition.length-1]) //condition[condition.length-1] return currency
{
cond = true;
console.log(key + " : "+value);
}
}
function traverse(o,func) {
for (var i in o) {
func.apply(this,[i,o[i]]);
if (o[i] !== null && typeof(o[i])=="object") {
if(cond === false)
{
traverse(o[i],func);
}
}
}
}
traverse(SampleJSON, process);
The above code print the first occurrence of the "Currency" element but I just want to print the element based on the arg1 which is given by user, and want to replace that value based on arg2.
is there any npm package available to achieve this?
Any help would be highly appreciated.