Skip to main content

camelCase to snake_case or snake_case to camelCase for Python dict object

Project description

# camel-and-snake

## 🐫 and 🐍 ???🤣

本项目旨在解决 camelCase 和 snake_case 相互转换的问题

**支持 python3 以上版本**


## 应用场景

* 生成对 JavaScript 更友好的 `camelCase` 命名规范的 JSON 响应数据
* 在 JSON 序列化之前将 `snake_case` 的字典转为 `camelCase`
* 在 JSON 反序列化之后将 `camelCase` 的字典转回 `snake_case`


## 如何使用?

### 安装

你可以通过 `pip` 来安装 `camel_and_snake`
> 推荐使用 `pipenv` 在虚拟环境下安装

```shell
$ pip3 install camel_and_snake
```


### 使用

```python
from camel_and_snake import Converter
```

**snake_case -> camelCase**

```python
dict_obj = {
'org_id': 123,
'org_name': 'ShadowCoder',
'member_list': [
{'member_id': 1, 'member_name': 'Cphayim'},
{'member_id': 2, 'member_name': 'Hoyoe'}
]
}

# 转换过程中将对深层的每一个字典进行递归替换 key 值,并返回一个新的对象
json.dumps(Converter.camelify(dict_obj), indent=2)

"""
{
"orgId": 123,
"orgName": "ShadowCoder",
"memberList": [
{
"memberId": 1,
"memberName": "Cphayim"
},
{
"memberId": 2,
"memberName": "Hoyoe"
}
]
}
"""
```


**camelCase -> snake_case**

```python
json_str = '{"orgId": 123, "orgName": "ShadowCoder", "memberList": [{"memberId": 1, "memberName": "Cphayim"}, {"memberId": 2, "memberName": "Hoyoe"}]}'

dict_obj = Converter.snakeify(json.loads(json_str))
# {'org_id': 123, 'org_name': 'ShadowCoder', 'member_list': [{'member_id': 1, 'member_name': 'Cphayim'}, {'member_id': 2, 'member_name': 'Hoyoe'}]}
```

## License

[MIT](https://opensource.org/licenses/MIT)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

camel_and_snake-0.1.2.tar.gz (3.0 kB view hashes)

Uploaded Source

Built Distribution

camel_and_snake-0.1.2-py3-none-any.whl (3.4 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page