Home > Back-end >  Convert string snake_case to camelCase in python [closed]
Convert string snake_case to camelCase in python [closed]

Time:09-21

I have a dictionary that looks like this:

json = {
    "id": 5,
    "item_id": 10,
    "some_random_name": "asddsa"
}

I want to convert it to look like this:

json = {
    "id": 5,
    "itemID": 10,
    "someRandomName": "asddsa"
}

So far I've tried using pyhumps and inflection libraries, but they fail on the id part. They return this:

json = {
    "id": 5,
    "itemId": 10,
    "someRandomName": "asddsa"
}

CodePudding user response:

I use a brute-force approach for the id --> ID conversion, then regex.

import json
import re

json_d = {
    "id": 5,
    "item_id": 10,
    "some_random_name": "asddsa"
}
j_str = json.dumps(json_d)
j_str = j_str.replace('_id', 'ID')

j_str_camel = re.sub(r'(_[a-z])', lambda m: None if m is None else m.group(0)[1:].upper(), j_str)

j_d_camel = json.loads(j_str_camel)

print(j_d_camel)

Output

{'id': 5, 'itemID': 10, 'someRandomName': 'asddsa'}

Remark: it applied the pattern on the serialized json dictionary since not stated otherwise in the question. If only for keys than iterate over a loop apply the pattern, for example, to a new dictionary or apply a better global regex

EDIT: without any extra modules (and side effects)

Create a new dictionary with key-names as in question, "non-default" camelcase, values not affected

json_d = {
    "id": 5,
    "item_id": 10,
    "some_random_name": "asddsa"
}

json_d_new = {}

for k, v in json_d.items():
    if '_id' in k:
        json_d_new[k.replace('_id', 'ID')] = v
    if '_' in k:
        json_d_new[''.join(w[0].upper()   w[1:] if i >0 else w for i, w in enumerate(k.split('_')))] = v

print(json_d_new)

# {'itemID': 10, 'itemId': 10, 'someRandomName': 'asddsa'}

CodePudding user response:

use this, i handled your problem with 'Id'
def camel_case_converter(json):
    new_json = {}
    for key in json:
        words = key.split('_')
        camel_case_key = ''.join(
            word[0].upper()   word[1:].lower() for word in words
        )
        camel_case_key = camel_case_key[0].lower()   camel_case_key[1:]
        camel_case_key = camel_case_key.replace('Id', 'ID')

        new_json[camel_case_key] = json[key]

    return new_json
or you can use this package:
import stringcase
stringcase.camelcase('some_random_name') # => "someRandomName"
  • Related