简单的方法来修改json的键从snake_case到camelCase
我有很多的JSONparsing和所有的JSON我收到的是有像在user_name
蛇情况下的键。 而parsing我需要它像骆驼像userName
情况下。
示例json文件如下所示:
[{ "user_id" : 1, "user_name" : "Abcd" }, { "org_id" : 11, "org_name" : "some_name" } ... ]
预期产出:
[{ "userId" : 1, "userName" : "Abcd" }, { "orgId" : 11, "orgName" : "some_name" } ... ]
我正在收到的JSON没有任何特定的固定标记,它可以是任何东西。 但所有的钥匙将在蛇的情况下。 我需要将其转换为camelCase。
我不能做的是find和replace,因为它也取代了蛇套pipestring。
有没有简单的方法,可以做到这一点?
您可以使用名为camelcase-keys-deep
npm包
您可以执行以下操作:
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(/_([az])/g, function (g) { return g[1].toUpperCase(); }); newValue[key] = value; keys.push(newValue); } }); } //console.log(keys);
希望这可以帮助 :)
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);
所以AKSHAY JAIN的实现非常稳定,但是它会删除那些不是蛇的属性。 我修正了这个实现。
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);