formatting json data to be camelCased

前端 未结 5 1681
一整个雨季
一整个雨季 2021-02-13 13:57

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

{
    \"Response\": {
        \"FirstName\": \"John\",
        \"LastName\": \"Smith\",
            


        
5条回答
  •  不要未来只要你来
    2021-02-13 14:32

    The approach that user '@I Hate Lazy' suggested - using a 'reviver' function is - the right one. However his function didn't work for me.

    Perhaps it is because I'm parsing a JSON array. Also I use Resharper and it complained about a code smell :) ('not all code paths return a value'). So I ended up using a function from another SO issue which did work for me:

    function camelCaseReviver(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;
    }
    

提交回复
热议问题