将json数据格式化为驼峰式 [英] formatting json data to be camelCased

查看:1252
本文介绍了将json数据格式化为驼峰式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从服务器收到一个类似于以下内容的json响应:

I get a json response from the server that looks something like this:

{
    "Response": {
        "FirstName": "John",
        "LastName": "Smith",
        "NickNames": {
            "NameOne": "Johnny",
            "NameTwo": "JohnS",
            "NameThree": "Smithy"
        },
        "Success": true,
        "Errors": []
    }
}

有没有一种方法可以通过函数运行此响应,以便每个键值对的键都被驼峰化?

Is there a way I can run this response through a function so that the key of each key value pair would be camelCased?

所以输出看起来像:

{
    "response": {
        "firstName": "John",
        "lastName": "Smith",
        "nickNames": {
            "nameOne": "Johnny",
            "nameTwo": "JohnS",
            "nameThree": "Smithy"
        },
        "success": true,
        "errors": []
    }
}

如果有人可以将我指向正确的方向,那就太好了.

If someone could point me in the right direction, that'd be great.

谢谢.

推荐答案

您将给JSON.parse一个齐磊的函数,该函数将值分配给小写的新属性.

You would give JSON.parse a reviver function that assigns values to new properties that are lower-cased.

function toCamelCase(key, value) {
  if (value && typeof value === 'object'){
    for (var k in value) {
      if (/^[A-Z]/.test(k) && Object.hasOwnProperty.call(value, k)) {
        value[k.charAt(0).toLowerCase() + k.substring(1)] = value[k];
        delete value[k];
      }
    }
  }
  return value;
}

var parsed = JSON.parse(myjson, toCamelCase);

有关其工作原理的更多信息,在此解答中.

More information about how it works in this SO answer.

这篇关于将json数据格式化为驼峰式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆