I encountered an issue while attempting to manipulate/retrieve the JSON value using REGEX, resulting in an undefined return

I am attempting to retrieve the currency value from a JSON file and if it is USD, then I want to change it to AUD.

When trying to find the currency attribute in the JSON file, it returned 'undefined' as shown 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"
      }
   ]
}

Could someone assist me on how to update the currency value in the JSON file and why it is returning 'undefined'?

Thank you for your help.

Updated:

The data.json file is dynamic, with its structure changing every few minutes. My focus is solely on retrieving the currency attribute which is always present in the data.json file and updating the JSON before sending it to the server.

Answer №1

The regular expression seems to be incorrect. You may want to attempt using

/"currency":"([^"]*)"/
.

Answer №2

When dealing with structured data like JSON, performing a string match may lead to more issues than solutions. If the data follows a consistent structure, it is best to manipulate it based on that structure. On the other hand, if the data is not consistently structured, relying on string manipulation can be unreliable.

Although your regex pattern is simple, it contains some errors:

/"currency":(^")*/
  • "currency": will match exactly as written (assuming no extra whitespace)
  • (: starts a capturing group
  • ^: indicates the start of the string, which is incorrect in this context
  • ": matches a literal "
  • )*: ends the capturing group and allows for zero or more occurrences

It seems like you intended to use [^"] instead of (^"), meaning "any character except "". However, this would not work due to the " immediately following the colon.

Consider using + instead of * for "one or more", or specifying the exact number of characters using {3}.

To capture the entire 3-character currency code, ensure the brackets encapsulate the full expression:

/"currency":"([^"]+)"/

You could also simplify the pattern by using three wildcard characters:

/"currency":"(...)"/

Answer №3

Here is a sample of how this can be accomplished.

let information = {
   "bank":[
      {
         "accountType":"Savings",
         "country":"US",
         "currency":"USD",
         "firstName":"John",
         "lastName":"Doe",
         "verified":"true"
      }
   ]
};

var dataString = JSON.stringify(information);

console.log(dataString);

var match = /"currency":\"[A-Z]{3}\"/.exec(dataString)[0];

let currencyValue = match.split(":")[1].replaceAll('"', '');

console.log(currencyValue);

//You can also access the currency directly from the data

console.log(information.bank[0].currency);

//If the data is in string format, you can use the JSON.parse() function to convert it into a JSON object.

//https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

//Assuming that you have the JSON as a string:

let jsonObject = JSON.parse(dataString);

console.log(jsonObject.bank[0].currency);

//To replace USD with AUD for example:

jsonObject.bank[0].currency = jsonObject.bank[0].currency.replace("USD", "AUD");

console.log(jsonObject.bank[0].currency);

Answer №4

To convert currency from USD to AUD, you can utilize the following regex;

/(?<="currency":")[^"]+/

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

var datastring = JSON.stringify(data);
const replacedString = datastring.replace(/(?<="currency":")[^"]+/, "AUD");
console.log(replacedString);

Answer №5

let userData = {
  customer: [
    {
      userType: 'Guest',
      country: 'Canada',
      currency: 'CAD',
      firstName: 'John',
      lastName: 'Doe',
      confirmed: 'true'
    }
  ]
}
let userDataString = JSON.stringify(userData)
let updatedCurrency = userDataString.replace(/"currency":"([^"]*)"/, '"currency":"EUR"')
let parsedData = JSON.parse(updatedCurrency)
console.log(parsedData)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to link the id selector with the item's id?

In my app, I have a list of items with buttons that can be liked. To ensure uniqueness, I am utilizing the id selector. My goal is to use the item's id and connect it to the id selector for proper distinction. How can I retrieve the id of each item a ...

Animating Jquery to smoothly change opacity until it reaches 100% visibility

The script I have does several things, but the main issue lies in the last line where the opacity of the class doesn't seem to reach 100%.... $('.fa-briefcase').parent().on('click', function () { $("#colorscreen").remove(); ...

Move the cursor within the text area upon clicking the button

When the "+header" button is clicked, I am looking to automatically position the insertion point inside the text area. Currently, after pressing the button, the text box displays information like address, date, time etc. but the cursor does not start insid ...

Function activation in Element requires a double click to initiate

I've encountered an issue with a web element I'm working on where the click function only triggers after the first click, rendering the initial click ineffective. Here's the code snippet in question: HTML: <div> <a href="#0" cla ...

JQGrid is a unique event grid that triggers only once for the inaugural loading, allowing users to apply a default filter upon first loading

I am currently using JQGrid (jQuery jQgrid not Gurrido) version 4.6.0 and I am in need of an event that occurs only once the grid has completed loading for the first time. I have attempted to use loadComplete and gridComplete, but it seems they both perfor ...

Subscription date is activated when a different part of the state changes in ngrx

Within my state, I have properties named start and end which store dates. Whenever any other part of the state is modified, the subscription for these start and end dates is triggered. Here is the subscription implementation: this.subs.sink = this.store ...

The paragraph text should dynamically update upon clicking a button based on JavaScript code, however, the text remains unchanged despite attempts to modify it

I recently started learning JavaScript and wanted to update the content of a paragraph when a button is clicked. However, I encountered an issue where this functionality doesn't seem to work. <body> <p id="paragraph">Change Text on cl ...

Is there a way to access an object stored on my server using JavaScript?

In implementing JavaScript, I wish to define two objects stored in a file named file.txt, and utilize them within my code. For instance, I have included the following snippet in my index.php: var counter = Number(localStorage.getItem('rans')) ...

Encountered an issue when trying to establish a connection to the MySQL database on Openshift using a

I am currently running a Node.js app with Express that is deployed on OpenShift. I have set up databases using the PHPMyAdmin 4.0 cartridge. Although I can establish a connection to the database, anytime I run a query, it throws an ECONNREFUSED error. Whe ...

Monitoring Javascript inactivity timeouts

As I work to incorporate an inactivity timeout monitor on my page, the goal is to track whether individuals working from home are present at their desks or not. The Jquery plugin http://plugins.jquery.com/project/timeout that I am utilizing initiates a ti ...

ajax request fetching new data upon webpage reload

I'm encountering an issue where a JSON jQuery call only works when the page is refreshed after loading. Meaning, on initial page load, the data is not updated, but upon refreshing the page, the data is refreshed successfully. This data feeds into a se ...

I am using jQuery Ajax and PHP to receive data in JSON format

Hey there, I've been trying to retrieve a 2-dimensional array from PHP using Ajax and jQuery, but I'm having trouble getting a response. Here's the code I have: HTML code $.ajax({ type: "POST", url: "get_data.php", data: "", ...

Exploring the existence of properties using nuxt js

Hello there, I'm currently checking for the existence of {{data.name}}. If it doesn't exist, simply do not display it. Here are some iterations: <div v-if="conts.Titre || conts.keys(conts.Titre).length > 0" class="communes-contenu"> & ...

Exploring the connections between numerous rows that illustrate a one-to-many connection

Imagine a scenario where there is a student who has a one-to-many relationship with books. When querying the related tables in Python, the result appears in a flat format: (Assuming I am using psycopg and raw SQL to fetch records from the database) ...

Generating intricate JSON data structures with a combination of WCF LINQ-to-SQL and REST in C# ASP.NET

Within my web application, there is a login page where users can log in. Once logged in, I need to retrieve the Account object, which contains an EntitySet of Player: public Account Login(string email, string password) { var query = (from p in db.Acco ...

The Bootstrap 4 card component is a versatile and stylish

Currently working on a display layout using Bootstrap 4, specifically utilizing cards. The issue I'm facing is that the text exceeds the limit of the card, causing it to overflow. Is there a solution to make the text automatically wrap to the bottom ...

Trouble arises when adding a .js script to the webpage

I'm feeling quite puzzled by this small piece of code, as it appears to be the simplest thing you'll come across today. Despite that, I can't help but seek guidance because I've been staring at it for what feels like an eternity and can ...

Merging data from different columns in a table to form a JSON structure

I have a database set up in athena that contains the following information: type state city zipcode ------------------------------- hot az phx 85281 hot tx dal 12345 cool wa sea 67890 cool ny nyc 67856 My g ...

Node's Object.prototype function returns an empty object

When I run Object.prototype in the browser console, I see all the properties and methods within it. However, when I do the same thing in the NodeJS terminal, I get an empty object {}. Can someone explain why this difference occurs? Attached are screenshots ...

Triumph awaits before the final response is delivered

Being new to web development, I am currently working on my first web application using purely node.js. In the registration process, form data is sent from the client-side to the server and then stored in the database. Upon a successful response, the client ...