JSON.stringify, change the case of the key

You can use a JSON replacer to switch keys before writing.

JSON.stringify(myVal, function (key, value) {
  if (value && typeof value === 'object') {
    var replacement = {};
    for (var k in value) {
      if (Object.hasOwnProperty.call(value, k)) {
        replacement[k && k.charAt(0).toLowerCase() + k.substring(1)] = value[k];
      }
    }
    return replacement;
  }
  return value;
});

For the opposite, you can use a JSON reviver.

JSON.parse(text, function (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;
    });

The second optional argument is a function that is called with every value created as part of the parsing or every value about to be written. These implementations simply iterate over keys and lower-cases the first letter of any that have an upper-case letter.

There is documentation for replacers and revivers at http://json.org/js.html :

The optional reviver parameter is a function that will be called for every key and value at every level of the final result. Each value will be replaced by the result of the reviver function. This can be used to reform generic objects into instances of pseudoclasses, or to transform date strings into Date objects.

The stringifier method can take an optional replacer function. It will be called after the toJSON method (if there is one) on each of the values in the structure. It will be passed each key and value as parameters, and this will be bound to object holding the key. The value returned will be stringified.

Leave a Comment