简体   繁体   中英

Simple method to modify json keys casing to camelCase from snake_case

I have lots of json parsing and all the json I am receiving is having keys in snake case like user_name . And for parsing I need it in camel case like userName .

The sample json file would look like this:

[{
   "user_id" : 1,
   "user_name" : "Abcd"
},
{
   "org_id" : 11,
   "org_name" : "some_name"
}
...
]

Expected output:

[{
   "userId" : 1,
   "userName" : "Abcd"
},
{
   "orgId" : 11,
   "orgName" : "some_name"
}
...
]

The json I am receiving is not having any particular fixed notation and it can be anything. But all the keys will be in snake case. And I need to convert it to camelCase.

What I cannot do is, find and replace, because it also replace snake casing strings in values as well.

Is there any easy method, which can do the same?

You can use npm package called: camelcase-keys-deep

https://www.npmjs.com/package/camelcase-keys-deep

You can do the following:

var keys = [];//this will contain the json with desired output
for(var i = 0;i<myObj.length;i++)//myObj is the variable that contains your json
{
    Object.keys(myObj[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            var newValue = {};
            var value = myObj[i][key];
            key = key.replace(/_([a-z])/g, function (g) { return g[1].toUpperCase(); });
            newValue[key] = value;
            keys.push(newValue);
        }   
    });

}
//console.log(keys);

Hope this helps :)

 var arr = [{ "user_id": 1, "user_name": "Abcd" }, { "org_id": 11, "org_name": "some_name" } ]; arr.forEach(a => { Object.keys(a).forEach(k => { newK = k.replace(/(\\_\\w)/g, (m) => m[1].toUpperCase()); a[newK] = a[k]; delete a[k]; }); }); console.log(arr); 

So AKSHAY JAIN 's implementation is pretty solid but it will delete the properties that are not in snake case. I fixed the implementation.

var arr = [{
  "user_id": 1,
  "user_name": "Abcd"
},
{
  "org_id": 11,
"org_name": "some_name"
},
{
  "personId": 12,
  "personName": "otherName"
}];

arr.forEach(a => {
    Object.keys(a).forEach(k => {
      newK = k.replace(/(\_\w)/g, (m) => m[1].toUpperCase());
      if (newK != k) {
        a[newK] = a[k];
        delete a[k];
      }
    });
  });

console.log(arr);

If u use lodash I would suggest my solution for this:

snake_case -> camelCase

function camelCaseDeep(anything) {
  const thing = _.cloneDeep(anything);

  if (
    _.isEmpty(thing) ||
    (!_.isObject(thing) && !_.isArray(thing))
  ) {
    return thing;
  }

  if (_.isArray(thing)) {
    const arr = thing;
    return arr.map(el => camelCaseDeep(el))
  }

  // thing can be only not empty object here
  const objWithMappedKeys = _.mapKeys(thing, (value, key) => _.camelCase(key));
  const objWithMappedValues = _.mapValues(objWithMappedKeys, value => camelCaseDeep(value));

  return objWithMappedValues;
}

camelCase -> snake_case

function snakeCaseDeep(anything) {
  const thing = _.cloneDeep(anything);

  if (
    _.isEmpty(thing) ||
    (!_.isObject(thing) && !_.isArray(thing))
  ) {
    return thing;
  }

  if (_.isArray(thing)) {
    const arr = thing;
    return arr.map(el => snakeCaseDeep(el))
  }

  // thing can be only not empty object here
  const objWithMappedKeys = _.mapKeys(thing, (value, key) => _.snakeCase(key));
  const objWithMappedValues = _.mapValues(objWithMappedKeys, value => snakeCaseDeep(value));

  return objWithMappedValues;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM