- Published on
Converting JSON keys to upper or lower case in Typescript
Introduction
Table of Contents
Let's whip up a nifty TypeScript function to save the day. Here's how we can turn those lowercase keys into uppercase and vice versa:
type JSONValue = string | number | boolean | null | JSONObject | JSONArray
type JSONObject = { [key: string]: JSONValue }
type JSONArray = JSONValue[]
function convertCase(obj: JSONObject, toUpper: boolean): JSONObject {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [
toUpper ? key.toUpperCase() : key.toLowerCase(),
typeof value === 'object' && value !== null
? Array.isArray(value)
? value.map((item) =>
typeof item === 'object' && item !== null
? convertCase(item as JSONObject, toUpper)
: item
)
: convertCase(value as JSONObject, toUpper)
: value,
])
)
}
Breaking it Down
- We use
Object.entries()
to get key-value pairs. map()
transforms each pair of uppercase/lowercase keys.- For nested objects, we recursively call
convertCase()
. Object.fromEntries()
converts the pairs back into an object.
Usage Example
Let's see our function in action:
const originalJson = {
name: 'john',
age: 30,
address: {
street: 'main st',
city: 'anytown',
},
}
const converedJSON = convertCase(originalJson)
console.log(JSON.stringify(converedJSON, null, 2))
And voilà! Your JSON keys are now all convered. 🎉
Try It Yourself!
Use the interactive component below to convert your JSON keys to upper/lower case: