首页 > 解决方案 > 从用户输入的点符号修改 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)

标签: pythonjsonparsingdictionary

解决方案


最快的方法可能是基于分隔符拆分字符串和索引。例如:

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

推荐阅读