python - 从用户输入的点符号修改 python 字典
问题描述
我试图在我的 Django python 应用程序中提供一个类似 API 的接口,允许某人输入一个id
,然后还包括作为表单数据的请求的键/值。
例如,工单 111 的以下字段名称和值:
ticket.subject = Hello World
ticket.group_id = 12345678
ticket.collaborators = [123, 4567, 890]
ticket.custom_fields: [{id: 32656147,value: "something"}]
在后端,我有一个对应的 Dict 应该匹配这个结构(我会做验证)。像这样的东西:
ticket: {
subject: "some subject I want to change",
group_id: 99999,
collaborator_ids: [ ],
custom_fields: [
{
id: 32656147,
value: null
}
]
}
1)我不确定在那里解析点符号的最佳方法,以及 2)假设我能够解析它,我将如何更改 Dict 的值以匹配传入的值。我' d 想象一下可能有这些输入的类?
class SetDictValueFromUserInput(userDotNotation, userNewValue, originalDict)
...
SetDictValueFromUserInput("ticket.subject", "hello world", myDict)
解决方案
最快的方法可能是基于分隔符拆分字符串和索引。例如:
obj = "ticket.subject".split(".")
actual_obj = eval(obj[0]) # this is risky, they is a way around this if you just use if statements and predifined variables.
actual_obj[obj[1]] = value
要进一步索引对象ticket.subject.name
可能工作的位置,请尝试使用 for 循环。
for key in obj[1:-2]: # basically for all the values in between the object name and the defining key
actual_obj = actual_obj[key] # make the new object based on the value in-between.
actual_obj[obj[-1]] = value
推荐阅读
- apache - 不区分大小写的 URL 重写
- typescript - 覆盖 Subject.next 方法
- javascript - javascript:无法使用 array.every() 区分“真”和“假”
- r - 逻辑回归中不同因素的致死剂量 (LD50)
- javascript - 无法使用 @Input() 以角度传递道具
- python - 将图像拖到 Kivy 上的目标时消失的图像
- typeclass - 如何证明原始类型类定义之外的类型类的定理?
- c# - 在 C# 中将请求正文转换为数据表或数据集
- javascript - 如何使用 Django URL 在 JavaScript 中传递字符串变量?
- android - 如何在红色文件夹中创建菜单文件夹