【问题标题】:Modifying a python dictionary from user inputted dot notation从用户输入的点符号修改 python 字典
【发布时间】:2018-05-16 01:22:09
【问题描述】:

我正在尝试在我的 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)

【问题讨论】:

    标签: python json parsing dictionary


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2021-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 2012-03-11
      • 1970-01-01
      相关资源
      最近更新 更多