formatting json data to be camelCased

前端 未结 5 1595
一整个雨季
一整个雨季 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:23

    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.

提交回复
热议问题