Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatting json data to be camelCased

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?

So the output would look something like:

{
    "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.

Thanks.

like image 476
Jeff Avatar asked Nov 26 '12 00:11

Jeff


1 Answers

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.

like image 146
I Hate Lazy Avatar answered Oct 21 '22 22:10

I Hate Lazy