Link to home
Start Free TrialLog in
Avatar of Nika Gudge
Nika GudgeFlag for United States of America

asked on

javascript regex

var request = "{ "merchantRef":"ffd031516002"";

function camelToUnderscore(str) {

      return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); //merchant_ref

}

i would want to return merchant_ref matching string before ":
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

var request = "{ "merchantRef":"ffd031516002"";

Open in new window

This is not valid JavaScript - it will throw an error.

It is not clear what you are asking. The above "script" looks like it is creating a JSON string - but it is badly formed. In a JSON string the ':' is not part of the data.

Can you explain what it is you are wanting to do?
Avatar of Nika Gudge

ASKER

{ "merchantRef":"ffd031516002", "TeleType":"score", "originalType":"card", "originalId":"1231231", "amount":"1100", "currencyCode":"USD" }

I have a json stringlike above. I need to convert the camelcase to underscore with lowercase key only not the value.

Required output:
 
{ "merchant_ref":"ffd031516002", "tele_type":"score", "original_type":"card", "original_id":"1231231", "amount":"1100", "currency_code":"USD" }
Thank you - that makes it a lot clearer.

<script>
function camelToUnderscore(str) {
	return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); //merchant_ref
}

var json = '{ "merchantRef":"ffd031516002", "TeleType":"score", "originalType":"card", "originalId":"1231231", "amount":"1100", "currencyCode":"USD" }';
var obj = JSON.parse(json);
var newObj = {};
for(var o in obj) {
  var newKey = camelToUnderscore(o);
  newObj[newKey] = obj[o];
}
var backToJson = JSON.stringify(newObj);
console.log(backToJson);
</script>

Open in new window

var data = '{ "merchantRef":"ffd031516002", "TeleType":"score", "originalType":"card", "originalId":"1231231", "amount":"1100", "currencyCode":"USD" } ';
var regex = /([a-z])([A-Z])/;
var result = data.replace(regex, function(match, group1, group2) {
	return group1 + '_' + group2.toLowerCase();
});

alert(result);

Open in new window


The regex looks for a lowercase letter followed by an uppercase letter. The function allows you to lowercase just the uppercase letter that was captured in capture group 2 (using the parentheses). This pattern will break data (i.e. values in your JSON) that also matches the pattern.
What if you get a data value that matches the CamelCase rule? The answer above won't discriminate between keys and values.
This pattern will break data (i.e. values in your JSON) that also matches the pattern.

= )
i need a solution for camelcase.. im trying to decamalize
ex:
fooBar => foo_bar

but only for the keys in json and not the values
Then you should use Julian's JSON.parse approach. I was just attempting a regex-only solution, but it has the aforementioned caveat.
@Julian Hansen: i'm having json with nested objects.

Your code snippet breaks
For example: the above code snippet will fail for nested objects

'{ "merchantRef":"ffd031516002", "TeleType":"score", "originalType":"card", "originalId":"1231231", "amount":"1100", "currencyCode":"USD","customer":{"id":"125Xasdf57D","startDate":"2017-01-04","firstName":"John","lastName":"Smith","middleName":"First","email":"accept@xyz.com"} }'
You should post an example JSON that is representative of the structure you are working with. We're not sitting right next to you; we can only guess at what you have or inspect what you provide us.
here you go the actual json. please find the attachment.
test.txt
For example: the above code snippet will fail for nested objects
The solution works for the the original data posted.
To cater for nested objects we would need to recursively iterate over the object.
<script>
var json = '{ ... }';
var obj = JSON.parse(json);
var newObj = ccToUscore(obj);
var backToJson = JSON.stringify(newObj);

function ccToUscore(obj)
{
  var newObj = {};
  
  for(var o in obj) {
    var newKey = camelToUnderscore(o);
    if (typeof obj[o] == 'object') {
      newObj[newKey] = ccTouscore(obj[o]);
    }
    else {
      newObj[newKey] = obj[o];    
    }
  }
  return newObj;
}

function camelToUnderscore(str) {
  return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); //merchant_ref
}
</script>

Open in new window

1. '[' brackets are converted to '{'
2. "0":{ is being added
before conversion ex:
"items": [
      {

after conversion ex:
"items":{
"0":{
Before
{
   "merchantRef":"ffd031516002",
   "transactionType":"score_only",
   "originalTransactionType":"transaction",
   "originalTransactionId":"1231231",
   "amount":"1100",
   "currencyCode":"USD",
   "customer":{
      "id":"125Xasdf57D",
      "startDate":"2017-01-04",
      "firstName":"John",
      "lastName":"Smith",
      "middleName":"First",
      "email":"accept@xyz.com",
      "sessionId":"session-1",
      "username":"username",
      "gender":"male",
      "dateOfBirth":"2017",
      "address":{
         "street":"123 Main Street",
         "street2":"Apartment 123",
         "stateProvince":"NY",
         "city":"New York",
         "country":"US",
         "phone":{
            "type":"cell",
            "number":"212-515-1212"
         },
         "zipPostalCode":"11375"
      }
   },
   "billingAddress":{
      "firstName":"John",
      "lastName":"Smith",
      "middleName":"First",
      "street":"123Mainstreet",
      "stateProvince":"NY",
      "city":"NewYork",
      "country":"CAN",
      "phone":{
         "type":"cell",
         "number":"212-515-1212"
      },
      "zipPostalCode":"11375"
   },
   "device":{
      "deviceType":"device/mobile",
      "deviceId":"BDE000:008945:58AC03:F02569",
      "networks":[
         {
            "networkType":"network/wifi",
            "ip":"10.201.0.244",
            "mac":"02:00:00:00:00:00",
            "ssid":"Boston-5G-1",
            "bssid":"e8:fc:af:fb:4b:8c"
         }
      ],
      "latitude":90.0,
      "longitude":90.0,
      "imei":"49-015420-323751",
      "model":"iphone",
      "manufacturer":"apple",
      "timezoneOffset":"+02:00",
      "rooted":false,
      "malwareDetected":false,
      "userDefined":{
         "battery":"5h 10m",
         "uptime":"0.95"
      }
   },
   "loyalty":{
      "id":"LY342XYS",
      "program":"GOLD",
      "balance":200
   },
   "payment":{
      "paymentType":"payment/card",
      "method":{
         "methodType":"method/card",
         "methodId":"123",
         "methodAlias":"card_method",
         "card":{
            "cardholderName":"John Smith",
            "cardNumber":"444444444444",
            "expDate":"122018",
            "cvvPresent":false,
            "issuer":"Bank of America",
            "cardReissuedNumber":"3"
         },
         "provider":"apple"
      },
      "pinPresent":false,
      "cardBrand":"VISA",
      "entryMethod":"remote",
      "issuerResponse":{
         "code":"000",
         "status":"approved",
         "scheme":"visa",
         "issuerApprovedAmount":"8000",
         "cardBalance":"9000"
      },
      "verificationAvs":{
         "code":"1",
         "status":"2",
         "scheme":"3"
      },
      "verification3ds":{
         "code":"4",
         "status":"approved",
         "scheme":"6"
      },
      "verificationCvv":{
         "code":"7",
         "status":"approved",
         "scheme":"9"
      },
      "userDefined":{
         "failedPinAttempts":"20"
      }
   },
   "merchant":{
      "merchantUniqueId":"WALLET",
      "location":{
         "locationId":"WALLET",
         "merchantAddress":{
            "street":"123 Main street",
            "street2":"St",
            "stateProvince":"NY",
            "city":"New York",
            "country":"US",
            "zipPostalCode":"11375"
         },
         "timeZoneOffset":"-05:00",
         "hierarchy":"abc"
      },
      "mcc":"7311"
   },
   "order":{
      "shipToAddress":{
         "phone":"123-123-1234",
         "address_1":"123 Second Ave.",
         "address_2":"222",
         "city":"Atlanta",
         "state":"GA",
         "zip":"30024",
         "country":"UK"
      },
      "items":[
         {
            "id":"1234",
            "name":"mouse",
            "quantity":"6",
            "unit":"carret",
            "unitPrice":"1299",
            "categories":[
               [
                  "Books",
                  "Computer",
                  "Programming"
               ],
               [
                  "Books",
                  "Text Books",
                  "Computer Science"
               ]
            ],
            "detailsUrl":"https://mystore.domain/product/978-0321751041",
            "userDefined":{
               "weight":"5021.23",
               "vat":"0.06"
            }
         }
      ],
      "detailsUrl":"https://mystore.domain/product/978-0321751041",
      "userDefined":{
         "delivery":"express",
         "carrier":"ups"
      }
   },
   "userDefined":{
      "inauthTransId":"1234"
   }
}

Open in new window

After
{
   "merchant_ref":"ffd031516002",
   "transaction_type":"score_only",
   "original_transaction_type":"transaction",
   "original_transaction_id":"1231231",
   "amount":"1100",
   "currency_code":"USD",
   "customer":{
      "id":"125Xasdf57D",
      "start_date":"2017-01-04",
      "first_name":"John",
      "last_name":"Smith",
      "middle_name":"First",
      "email":"accept@xyz.com",
      "session_id":"session-1",
      "username":"username",
      "gender":"male",
      "date_of_birth":"2017",
      "address":{
         "street":"123 Main Street",
         "street2":"Apartment 123",
         "state_province":"NY",
         "city":"New York",
         "country":"US",
         "phone":{
            "type":"cell",
            "number":"212-515-1212"
         },
         "zip_postal_code":"11375"
      }
   },
   "billing_address":{
      "first_name":"John",
      "last_name":"Smith",
      "middle_name":"First",
      "street":"123Mainstreet",
      "state_province":"NY",
      "city":"NewYork",
      "country":"CAN",
      "phone":{
         "type":"cell",
         "number":"212-515-1212"
      },
      "zip_postal_code":"11375"
   },
   "device":{
      "device_type":"device/mobile",
      "device_id":"BDE000:008945:58AC03:F02569",
      "networks":{
         "0":{
            "network_type":"network/wifi",
            "ip":"10.201.0.244",
            "mac":"02:00:00:00:00:00",
            "ssid":"Boston-5G-1",
            "bssid":"e8:fc:af:fb:4b:8c"
         }
      },
      "latitude":90,
      "longitude":90,
      "imei":"49-015420-323751",
      "model":"iphone",
      "manufacturer":"apple",
      "timezone_offset":"+02:00",
      "rooted":false,
      "malware_detected":false,
      "user_defined":{
         "battery":"5h 10m",
         "uptime":"0.95"
      }
   },
   "loyalty":{
      "id":"LY342XYS",
      "program":"GOLD",
      "balance":200
   },
   "payment":{
      "payment_type":"payment/card",
      "method":{
         "method_type":"method/card",
         "method_id":"123",
         "method_alias":"card_method",
         "card":{
            "cardholder_name":"John Smith",
            "card_number":"444444444444",
            "exp_date":"122018",
            "cvv_present":false,
            "issuer":"Bank of America",
            "card_reissued_number":"3"
         },
         "provider":"apple"
      },
      "pin_present":false,
      "card_brand":"VISA",
      "entry_method":"remote",
      "issuer_response":{
         "code":"000",
         "status":"approved",
         "scheme":"visa",
         "issuer_approved_amount":"8000",
         "card_balance":"9000"
      },
      "verification_avs":{
         "code":"1",
         "status":"2",
         "scheme":"3"
      },
      "verification3ds":{
         "code":"4",
         "status":"approved",
         "scheme":"6"
      },
      "verification_cvv":{
         "code":"7",
         "status":"approved",
         "scheme":"9"
      },
      "user_defined":{
         "failed_pin_attempts":"20"
      }
   },
   "merchant":{
      "merchant_unique_id":"WALLET",
      "location":{
         "location_id":"WALLET",
         "merchant_address":{
            "street":"123 Main street",
            "street2":"St",
            "state_province":"NY",
            "city":"New York",
            "country":"US",
            "zip_postal_code":"11375"
         },
         "time_zone_offset":"-05:00",
         "hierarchy":"abc"
      },
      "mcc":"7311"
   },
   "order":{
      "ship_to_address":{
         "phone":"123-123-1234",
         "address_1":"123 Second Ave.",
         "address_2":"222",
         "city":"Atlanta",
         "state":"GA",
         "zip":"30024",
         "country":"UK"
      },
      "items":{
         "0":{
            "id":"1234",
            "name":"mouse",
            "quantity":"6",
            "unit":"carret",
            "unit_price":"1299",
            "categories":{
               "0":{
                  "0":"Books",
                  "1":"Computer",
                  "2":"Programming"
               },
               "1":{
                  "0":"Books",
                  "1":"Text Books",
                  "2":"Computer Science"
               }
            },
            "details_url":"https://mystore.domain/product/978-0321751041",
            "user_defined":{
               "weight":"5021.23",
               "vat":"0.06"
            }
         }
      },
      "details_url":"https://mystore.domain/product/978-0321751041",
      "user_defined":{
         "delivery":"express",
         "carrier":"ups"
      }
   },
   "user_defined":{
      "inauth_trans_id":"1234"
   }
}

Open in new window

This approach should hone in on only the keys:

var key_regex = /"([a-zA-Z]+)"\s*:/g;
var result = data.replace(key_regex, function(match, group1) {
    var replacement_regex = /([a-z])([A-Z])/g;
    var newKey = group1.replace(replacement_regex, function(match, group1, group2) {
      return `${group1}_${group2.toLowerCase()}`;
  });
  
  return `"${newKey}":`;
});

Open in new window


https://jsfiddle.net/rajw15uz/14/
@ Julian Hansen,

Please see the section for items before and after

"items":[
         {
            "id":"1234",
            "name":"mouse",
            "quantity":"6",
            "unit":"carret",
            "unitPrice":"1299",
            "categories":[
               [
                  "Books",
                  "Computer",
                  "Programming"
               ],
               [
                  "Books",
                  "Text Books",
                  "Computer Science"
               ]
            ],
            "detailsUrl":"https://mystore.domain/product/978-0321751041",
            "userDefined":{
               "weight":"5021.23",
               "vat":"0.06"
            }
         }
      ],
@ käµfm³d 👽:

your solution works. But i get this in output:

{ "${newKey}":"ffd031516002", "${newKey}":"score_only", "${newKey}":"transaction/purchase", "${newKey}":"fraudFAPI1231231", "${newKey}":"1100", "${newKey}":"USD", "${newKey}":{ "${newKey}":"125Xasdf57D", "${newKey}":"2017-01-04", "${new
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thank you both. Liked your solutions.
For anyone reading this - here is the code that takes into account arrays
<script>
function camelToUnderscore(str) {
  return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase(); //merchant_ref
}

var json = '{... }'; // JSON REMOVED
var obj = JSON.parse(json);
var newObj = ccTouscore(obj);
var backToJson = JSON.stringify(newObj);
console.log(backToJson);
function ccTouscore(obj)
{
  var newObj = {};
  
  for(var o in obj) {
    var newKey = camelToUnderscore(o);
    
    if (Array.isArray(obj[o])) {
      newObj[o] = [];
      obj[o].forEach(function(item) {
        newObj[o].push(ccTouscore(item));
      });
    }
    else if ((typeof obj[o]) == 'object') {
      newObj[newKey] = ccTouscore(obj[o]);
    }
    else {
      newObj[newKey] = obj[o];    
    }
  }
  
  return newObj;
}
</script>

Open in new window

Output
{
   "merchant_ref":"ffd031516002",
   "transaction_type":"score_only",
   "original_transaction_type":"transaction",
   "original_transaction_id":"1231231",
   "amount":"1100",
   "currency_code":"USD",
   "customer":{
      "id":"125Xasdf57D",
      "start_date":"2017-01-04",
      "first_name":"John",
      "last_name":"Smith",
      "middle_name":"First",
      "email":"accept@xyz.com",
      "session_id":"session-1",
      "username":"username",
      "gender":"male",
      "date_of_birth":"2017",
      "address":{
         "street":"123 Main Street",
         "street2":"Apartment 123",
         "state_province":"NY",
         "city":"New York",
         "country":"US",
         "phone":{
            "type":"cell",
            "number":"212-515-1212"
         },
         "zip_postal_code":"11375"
      }
   },
   "billing_address":{
      "first_name":"John",
      "last_name":"Smith",
      "middle_name":"First",
      "street":"123Mainstreet",
      "state_province":"NY",
      "city":"NewYork",
      "country":"CAN",
      "phone":{
         "type":"cell",
         "number":"212-515-1212"
      },
      "zip_postal_code":"11375"
   },
   "device":{
      "device_type":"device/mobile",
      "device_id":"BDE000:008945:58AC03:F02569",
      "networks":[
         {
            "network_type":"network/wifi",
            "ip":"10.201.0.244",
            "mac":"02:00:00:00:00:00",
            "ssid":"Boston-5G-1",
            "bssid":"e8:fc:af:fb:4b:8c"
         }
      ],
      "latitude":90,
      "longitude":90,
      "imei":"49-015420-323751",
      "model":"iphone",
      "manufacturer":"apple",
      "timezone_offset":"+02:00",
      "rooted":false,
      "malware_detected":false,
      "user_defined":{
         "battery":"5h 10m",
         "uptime":"0.95"
      }
   },
   "loyalty":{
      "id":"LY342XYS",
      "program":"GOLD",
      "balance":200
   },
   "payment":{
      "payment_type":"payment/card",
      "method":{
         "method_type":"method/card",
         "method_id":"123",
         "method_alias":"card_method",
         "card":{
            "cardholder_name":"John Smith",
            "card_number":"444444444444",
            "exp_date":"122018",
            "cvv_present":false,
            "issuer":"Bank of America",
            "card_reissued_number":"3"
         },
         "provider":"apple"
      },
      "pin_present":false,
      "card_brand":"VISA",
      "entry_method":"remote",
      "issuer_response":{
         "code":"000",
         "status":"approved",
         "scheme":"visa",
         "issuer_approved_amount":"8000",
         "card_balance":"9000"
      },
      "verification_avs":{
         "code":"1",
         "status":"2",
         "scheme":"3"
      },
      "verification3ds":{
         "code":"4",
         "status":"approved",
         "scheme":"6"
      },
      "verification_cvv":{
         "code":"7",
         "status":"approved",
         "scheme":"9"
      },
      "user_defined":{
         "failed_pin_attempts":"20"
      }
   },
   "merchant":{
      "merchant_unique_id":"WALLET",
      "location":{
         "location_id":"WALLET",
         "merchant_address":{
            "street":"123 Main street",
            "street2":"St",
            "state_province":"NY",
            "city":"New York",
            "country":"US",
            "zip_postal_code":"11375"
         },
         "time_zone_offset":"-05:00",
         "hierarchy":"abc"
      },
      "mcc":"7311"
   },
   "order":{
      "ship_to_address":{
         "phone":"123-123-1234",
         "address_1":"123 Second Ave.",
         "address_2":"222",
         "city":"Atlanta",
         "state":"GA",
         "zip":"30024",
         "country":"UK"
      },
      "items":[
         {
            "id":"1234",
            "name":"mouse",
            "quantity":"6",
            "unit":"carret",
            "unit_price":"1299",
            "categories":[
               {
                  "0":"Books",
                  "1":"Computer",
                  "2":"Programming"
               },
               {
                  "0":"Books",
                  "1":"Text Books",
                  "2":"Computer Science"
               }
            ],
            "details_url":"https://mystore.domain/product/978-0321751041",
            "user_defined":{
               "weight":"5021.23",
               "vat":"0.06"
            }
         }
      ],
      "details_url":"https://mystore.domain/product/978-0321751041",
      "user_defined":{
         "delivery":"express",
         "carrier":"ups"
      }
   },
   "user_defined":{
      "inauth_trans_id":"1234"
   }
}

Open in new window