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

Selecting list items using the up and down keys in JavaScript/jQuery

As the search terms dynamically populate a list of items, I am looking for a way to make the list items selectable/focused using the up/down keys and hide the dropdown with ESC key. <form> <div> <div class="field"> & ...

What sets onEnter apart from onStart in ui-router?

I am transitioning to the latest version of ui-router (1.0.0-alpha.5) and I am exploring how to utilize the onEnter hook versus the onStart hook: $transitions.onStart() as well as $transitions.onEnter() In previous versions, we only had the event $sta ...

Dynamically populate 7 select boxes with options using JQuery

I have a webpage that includes 14 different dropdown menus, one for each day of the week (Monday to Sunday). Each day has two dropdowns: one for opening time and one for closing time. I used jQuery to populate all 14 dropdowns with a pre-defined list of ho ...

Synchronously retrieving JSON data from a URL using JavaScript

I'm currently working on extracting the title of a YouTube video using jQuery to parse JSON. The issue I am facing is that it works asynchronously, resulting in the answer being displayed after the page has already loaded. Here's the current resu ...

How to apply a CSS class to the body element using Angular 2

I am working with three components in my Angular application: HomeComponent, SignInComponent, and AppComponent. The Home Page (HomeComponent) is displayed when the application is opened, and when I click the "Sign In" button, the signin page opens. I want ...

Exploring the intricacies of parsing nested JSON data

Could someone assist me with understanding the following json data? { "Message":"The request is invalid.", "ModelState":{ "model.ConfirmPassword":["The password and confirmation password do not match.","The password and confirmation passwo ...

What could be causing my form to malfunction when attempting to submit data using Ajax and an external PHP script that is handling two string inputs?

Hello, I am facing an issue while trying to utilize Ajax to interact with a PHP file and submit both inputs (fullname and phonenumber). When I click the submit button, it simply refreshes the page without performing the desired action. Below is the code I ...

What could be the reason for the ReferenceError that is being thrown in this code, indicating that '

let number = 1; console.log(number); Feel free to execute this basic code snippet. You may encounter an issue: ReferenceError: test is not defined, even though the variable was declared. What could be causing this unexpected behavior? ...

Assistance required with extracting information from JSON format on a website

Seeking assistance in displaying the last 10 songs played on a web page using JSON data. The current code is not fetching and showing the requested information from the json file. https://jsfiddle.net/Heropiggy95/6qkv7z3b/ Any help in identifying errors ...

What is the best way to display three unique maps simultaneously on separate views?

In this scenario, I have incorporated three separate divs and my goal is to integrate three maps into them. The javascript function that controls this process is as follows: function initialize() { var map_canvas1 = document.getElementById('map_canva ...

Is there a way to retrieve the hand-drawn lines at no cost in the form of a list, with each line represented as a collection of coordinates

I am currently contemplating the idea of utilizing fabric.js for an online handwriting recognition system. In order to make this system work, I need to transmit the sketched lines as a collection of lines, where each line consists of several points. If a ...

Utilizing the fetch() method to transmit GET data within the body rather than directly embedding it in the URL

I am in the process of converting this jQuery call to vanilla JavaScript using fetch() following the guidance provided by MDN (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options). $.ajax( { ...

Encountering Error: When Running the Command "npm run dev" it's Showing "missing script: dev" Message

I attempted to set up the SVELT GitHub repository locally by following these steps: https://github.com/fusioncharts/svelte-fusioncharts When I tried to launch it using the "npm run dev" command, I encountered this error: npm ERR! missing script: dev To ...

Code snippet: Retrieve the previous and upcoming events based on the current date from an array (JavaScript/Angular)

Is there anyone who can assist me with an algorithm? I have a list of events and need to retrieve the next event and previous events based on the current date. For example: I fetch all events from an SQL database like so: events = [ {eventId:1, event ...

To enhance the MUI v5 table row, simply apply a border when the mouse hovers

After working on creating a table with Material UI v5, I encountered an issue where I wanted to add a blue border to the table row when the mouse pointer hovered over it. I attempted several methods and did thorough research, but unfortunately, I was unab ...

React BrowserRouter causing issues with "invalid hook calls"

Just starting out with React and I am working on setting up paths using BrowserRouter, Route, and Routes in my code. import React from "react" import "./App.css"; import { BrowserRouter as Router, Route, Routes } from 'react-router ...

Is the .html page cached and accessible offline if not included in the service-worker.js file?

During the development of my PWA, I encountered an unexpected behavior with caching. I included a test .html page for testing purposes that was not supposed to be cached in the sw.js folder. Additionally, I added some external links for testing. However, w ...

Error: Attempting to access the 'clipboard' property on an undefined object results in a TypeError when invoking this.$q.electron.clipboard

I'm currently working on incorporating copy to clipboard functionality into my app using Electron. This is the command I am using: methods: { copyToClipboard () { if (process.env.MODE === 'electron') { this.$q.electro ...

The functionality of the Ajax script seems to be optimized for Firefox browsers exclusively, as it is encountering issues with compatibility on other

My code works perfectly in Firefox, but I'm encountering an issue in all other browsers. Specifically, I'm getting the error message "SyntaxError: JSON Parse error: Unexpected EOF" on line if (this.readyState == 4 && this.status == 200). ...

Issue with window.getSelection() function in Mozilla Firefox

I have implemented code to retrieve the window.getSelection() and assign it to a variable in order to store the current focusNode and offset when the contenteditable div onBlur event is triggered. This functionality works as expected in the Chrome browse ...