json下划线转驼峰
时间: 2023-09-17 17:11:31 浏览: 112
你可以使用以下的函数将 JSON 中的下划线转换为驼峰命名法:
```python
import re
def underscore_to_camelcase(word):
return re.sub(r'_(\w)', lambda m: m.group(1).upper(), word)
def convert_keys_to_camelcase(data):
if isinstance(data, dict):
new_data = {}
for key, value in data.items():
new_key = underscore_to_camelcase(key)
new_value = convert_keys_to_camelcase(value)
new_data[new_key] = new_value
return new_data
elif isinstance(data, list):
return [convert_keys_to_camelcase(item) for item in data]
else:
return data
```
你可以将 JSON 数据作为参数传递给 `convert_keys_to_camelcase` 函数,它将递归地遍历 JSON 数据并将所有的键转换为驼峰命名法。例如:
```python
import json
json_data = '{"first_name": "John", "last_name": "Doe", "age": 30}'
data = json.loads(json_data)
camelcased_data = convert_keys_to_camelcase(data)
camelcased_json = json.dumps(camelcased_data)
print(camelcased_json)
```
输出结果将会是:
```json
{"firstName": "John", "lastName": "Doe", "age": 30}
```
阅读全文