Skip to content

Unable to change/fetch the JSON value using REGEX and it returned Undefined

I’m trying to fetch the value of currency from the JSON file and if it’s USD then I need to change it to AUD.

When I tried to search the currency attribute in the json file return undefined as below:

Code:

var datastring = JSON.stringify(data);
var match = /"currency":(^")*/.exec(datastring);
console.log(match ? "Got " + match[1] : "No match");

Output: Got undefined

data.json:

{
   "bank":[
      {
         "bankAccountType":"Saving",
         "country":"US",
         "currency":"USD",
         "firstName":"TestFirstName",
         "lastName":"TestLastName",
         "confirmed":"true"
      }
   ]
}

Can someone help me how to update the currency value in the JSON file and why it’s returning ‘undefined’

Thanks in advance.

Updated:

The data.json is dynamic json file and the structure will differ in every few minutes of interval. I’m only interested to get currency attribute which is always available from the data.json file and update the json before invoke it to server.

Answer

const data = {
  bank: [
    {
      bankAccountType: 'Saving',
      country: 'US',
      currency: 'USD',
      firstName: 'TestFirstName',
      lastName: 'TestLastName',
      confirmed: 'true'
    }
  ]
}
const datastring = JSON.stringify(data)
const replace = datastring.replace(/"currency":"([^"]*)"/, '"currency":"AUD"')
const reparsed = JSON.parse(replace)
console.log(reparsed)