Skip to content

Instantly share code, notes, and snippets.

@elegantcoder
Created January 8, 2025 09:32
Show Gist options
  • Save elegantcoder/85b8bd4881f148f7a2f4dcb6b9ae1739 to your computer and use it in GitHub Desktop.
Save elegantcoder/85b8bd4881f148f7a2f4dcb6b9ae1739 to your computer and use it in GitHub Desktop.
camelizeJson

Example:

pbpaste | camelizeJson
#!/usr/bin/env python3
import sys, re, json
def camelize(input_string):
"""
Convert a string to camelCase.
"""
if not input_string:
return ""
words = re.split(r'[^a-zA-Z0-9]', input_string)
words = [word for word in words if word]
return words[0].lower() + ''.join(word.capitalize() for word in words[1:])
def camelize_json_keys(data):
"""
Recursively camelize JSON keys in a dictionary or list.
Args:
data: The JSON object to camelize. Can be a dictionary, list, or other types.
Returns:
The JSON object with camelCased keys.
"""
if isinstance(data, dict):
# Process dictionaries
return {camelize(key): camelize_json_keys(value) for key, value in data.items()}
elif isinstance(data, list):
# Process lists
return [camelize_json_keys(item) for item in data]
else:
# Base case: return data as is for non-dict, non-list
return data
if __name__ == "__main__":
try:
# Read JSON input from stdin
input_data = sys.stdin.read()
# Parse the JSON string
json_data = json.loads(input_data)
# Camelize the JSON keys
camelized_json = camelize_json_keys(json_data)
# Output the camelized JSON
print(json.dumps(camelized_json, indent=2))
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input. {e}", file=sys.stderr)
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment