Python Lambda函数解析DynamoDB的JSON格式
发布时间:2020-12-20 12:33:17 所属栏目:Python 来源:网络整理
导读:为dynamodb流调用的 Python Lambda函数具有具有DynamoDB格式的JSON(包含JSON中的数据类型).我想将DynamoDB JSON转换为标准JSON. PHP和nodejs有Marshaler可以做到这一点.如果Python有相似或其他选项,请告诉我. DynamoDB_format = `{"feas": {"M": { "fea": {
|
为dynamodb流调用的
Python Lambda函数具有具有DynamoDB格式的JSON(包含JSON中的数据类型).我想将DynamoDB JSON转换为标准JSON. PHP和nodejs有Marshaler可以做到这一点.如果Python有相似或其他选项,请告诉我.
DynamoDB_format = `{"feas":
{"M": {
"fea": {
"L": [
{
"M": {
"pre": {
"N": "1"
},"Li": {
"N": "1"
},"Fa": {
"N": "0"
},"Mo": {
"N": "1"
},"Ti": {
"S": "20160618184156529"
},"Fr": {
"N": "4088682"
}
}
}
]
}
}
}
}`
解决方法
更新:现在有一个图书馆:
https://pypi.org/project/dynamodb-json/
这是indiangolfer’s answer的改进版本. def unmarshal_dynamodb_json(node):
data = dict({})
data['M'] = node
return _unmarshal_value(data)
def _unmarshal_value(node):
if type(node) is not dict:
return node
for key,value in node.items():
# S – String - return string
# N – Number - return int or float (if includes '.')
# B – Binary - not handled
# BOOL – Boolean - return Bool
# NULL – Null - return None
# M – Map - return a dict
# L – List - return a list
# SS – String Set - not handled
# NN – Number Set - not handled
# BB – Binary Set - not handled
key = key.lower()
if key == 'bool':
return value
if key == 'null':
return None
if key == 's':
return value
if key == 'n':
if '.' in str(value):
return float(value)
return int(value)
if key in ['m','l']:
if key == 'm':
data = {}
for key1,value1 in value.items():
if key1.lower() == 'l':
data = [_unmarshal_value(n) for n in value1]
else:
if type(value1) is not dict:
return _unmarshal_value(value)
data[key1] = _unmarshal_value(value1)
return data
data = []
for item in value:
data.append(_unmarshal_value(item))
return data
它通过以下方式得到改进: >处理更多data types,包括以前未正确处理的列表 编辑:修复递归对象错误 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
