Since you inquired about using the reviver
method in the comment, here is a solution that demonstrates its usage.
However, the effectiveness of this approach is debatable.
It relies on the strategy employed during the reviving process, as outlined in 25.5.1 JSON.parse ( text [ , reviver ] ) and 25.5.1.1 InternalizeJSONProperty ( holder, name, reviver ), indicating that it should function correctly.
Yet, caution is advised when relying on this method, as the primary intent of the reviver functionality may not align with this particular use case. It might be better to reimplement the traversal logic instead.
this
within the reviver
callback pertains to the container that encompasses both key
and value
.
const str = `[{"user_id":"561904e8-6e45-5012-a9d8-e2ff8761acf6","email_addr":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="69030005061f290f08020c470a0604">[email protected]</a>","details":[{"city_name":"fake city","country_name":"fake country"}]},{"user_id":"5904003b-452b-535c-9615-94706bf6c66c","email_addr":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="40332137350026212b256e232f2d">[email protected]</a>","details":[{"city_name":"fake city","country_name":"fake country"}]}]`
const snakeToCamel = str => str.replace(/([-_]\w)/g, g => g[1].toUpperCase());
var parsed = JSON.parse(str, function(key, value) {
const camelCaseKey = snakeToCamel(key)
if (this instanceof Array || camelCaseKey === key) {
// if this is Array
// or key does not change after converted to camel case
// then just return the value so that the default "reviving" is done
return value
} else {
// if key changes assing value to camel case one and return nothing
this[camelCaseKey] = value
}
});
console.dir(parsed)
source of snakeToPascal