【问题标题】:Convert a string with the name of a variable to a dictionary将带有变量名称的字符串转换为字典
【发布时间】:2016-11-20 02:32:32
【问题描述】:

我有一个不太复杂的字符串,它有一些作为值嵌入的对象。我需要将它们转换为正确的 dict 或 json。

foo = '{"Source": "my source", "Input": {"User_id": 18, "some_object": this_is_a_variable_actually}}'

请注意,最后一个键 some_object 的值既不是字符串也不是 int。因此,当我执行json.loadsast.literal_eval 时,我收到格式错误的字符串错误,因此Converting a String to Dictionary 不起作用。

我无法控制字符串的来源。

这样的字符串可以转成字典吗

我需要的结果是这样的字典

dict = {
        "Source" : "Good",
        "object1": variable1,
        "object2": variable2
}

这里的问题是我不知道什么是变量 1 或 2。这里没有模式。

我想在这里提一点,如果我可以将变量设置为纯字符串,那也很好

例如,

dict = {
        "Source" : "Good",
        "object1": "variable1",
        "object2": "variable2"
}

这将有利于我的目的。谢谢大家的回答。

【问题讨论】:

  • 如果这是可能的,它怎么会知道如何评估this_is_a_variable_actually 并替换为那个变量值?
  • 我同意,但我的麻烦是我不知道这是 this_is_a_variable_actually 还是 i_dont_know_what_will_come_here。如果知道预期的结果,我会做一个字符串替换并完成它。
  • 您可以在包含this_is_a_variable_actually 定义的上下文中eval 它,但您最初是如何得到这个字符串的?
  • 我已经根据需要的结果修改了我的问题。

标签: python string dictionary


【解决方案1】:

使用 demjson 模块有点麻烦,它允许您解析大部分有点不确定的 JSON 语法字符串并列出错误...然后您可以使用它来替换找到并放置的无效标记引用它只是为了正确解析,例如:

import demjson
import re

foo = '{"Source": "my source", "Input": {"User_id": 18, "some_object": this_is_a_variable_actually}}'

def f(json_str):
    res = demjson.decode(json_str, strict=False, return_errors=True)
    if not res.errors:
        return res
    for err in res.errors:
        var = err.args[1]
        json_str = re.sub(r'\b{}\b'.format(var), '"{}"'.format(var), json_str)
    return demjson.decode(json_str, strict=False)

res = f(foo)

给你:

{'Input': {'User_id': 18, 'some_object': 'this_is_a_variable_actually'}, 'Source': 'my source'}

请注意,虽然这应该适用于所提供的示例数据,但如果您的输入中存在其他需要进一步修改的麻烦,您的里程可能会有所不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 1970-01-01
    • 2017-07-19
    • 2011-08-27
    • 2010-12-04
    • 2018-02-14
    相关资源
    最近更新 更多