Jeff Jeff - 1 year ago 77
jQuery Question

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.


Answer Source

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

function reviver(key, val) {
    if (key)
        this[key.charAt(0).toLowerCase() + key.slice(1)] = val;
        return val;

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

So if the key has at least one character, it will lowercase the first character and add on the rest, and add that key to the object, and allow the function to return undefined, so that the original key isn't used.

If the key has no characters, it just returns the value for the original processing.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download