如何将JSON对象的非规范键格式化为合规的标准键
规范化JSON对象的键名
需求说明
我有一个JSON对象,其中的键名不符合规范(包含空格、首字母大写等),需要将这些键名格式化为符合要求的形式,具体示例如下:
原JSON
{ "language": { "blogs details": "blogs details", "Search products": "Search products", "Somethings went wrong": "Somethings went wrong", "Become seller": "Become seller", "Cart": "Cart", "Your name": "Your Name", "Checkout": "Checkout" } }
期望得到的JSON
{ "language": { "blogs_details": "blogs details", "search_products": "Search products", "Somethings_went_wrong": "Somethings went wrong", "become_seller": "Become seller", "cart": "Cart", "your_name": "Your Name", "checkout": "Checkout" } }
解决方案
可以用JavaScript编写递归函数处理,核心逻辑是遍历JSON的每个键,将空格替换为下划线,同时把键名的首字母转为小写(仅修改键的第一个字符,后续单词的首字母保留原格式)。
代码实现
function normalizeJsonKeys(obj) { if (typeof obj !== 'object' || obj === null) { return obj; } if (Array.isArray(obj)) { return obj.map(item => normalizeJsonKeys(item)); } const normalizedObj = {}; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { // 替换空格为下划线,首字母转小写 let normalizedKey = key.replace(/\s+/g, '_'); normalizedKey = normalizedKey.charAt(0).toLowerCase() + normalizedKey.slice(1); normalizedObj[normalizedKey] = normalizeJsonKeys(obj[key]); } } return normalizedObj; } // 测试示例 const originalJson = { "language": { "blogs details": "blogs details", "Search products": "Search products", "Somethings went wrong": "Somethings went wrong", "Become seller": "Become seller", "Cart": "Cart", "Your name": "Your Name", "Checkout": "Checkout" } }; const normalizedJson = normalizeJsonKeys(originalJson); console.log(JSON.stringify(normalizedJson, null, 2));
代码说明
- 递归处理:支持嵌套的JSON对象和数组,确保所有层级的键都被规范化
- 键名转换规则:
- 用正则
/\s+/g将所有空格替换为下划线 - 仅将键名的第一个字符转为小写,后续字符保留原格式(比如"Somethings went wrong"转为"Somethings_went_wrong")
- 用正则
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

