从用户输入的点表示法修改python字典

时间:2018-05-16 01:22:10

标签: python json parsing dictionary

我正在尝试在我的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的值以匹配传入的内容。我想可能类似于带有这些输入的类?

class SetDictValueFromUserInput(userDotNotation, userNewValue, originalDict)
    ...

SetDictValueFromUserInput("ticket.subject", "hello world", myDict)

1 个答案:

答案 0 :(得分:1)

最快的方法可能是根据分离拆分字符串和索引。例如:

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