将字符串列表转换为python词典

2024-06-17 12:58:32 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有可能转换一个字典的字符串表示形式,其中的键不是用双引号括起来的

'{output:{OUTPUT_PATH:hdfs://x.x.x.x:X/tmp/x/x,OUTPUT_TYPE:hdfs},''input:{INPUT_TEMPTABLE:sample,INPUT_TYPE:hdfs,INPUT_PATH:hdfs://x.x.x.x:X/sparkStream/sample1/},''process:{query.param:${http.query.param.name},PROCESS_SQL:1,PROCESS_TYPE:sql},''attributes:{path:./,restlistener.remote.source.host:127.0.0.1,filename:1211999192960535,restlistener.remote.user.dn:none,uuid:2b025f49-7d53-49db-8063-24ddda29fc4a}}'

像这样的字典:

{"output":{"OUTPUT_PATH":"hdfs://x.x.x.x:X/tmp/x/x","OUTPUT_TYPE":"hdfs"},"input":{"INPUT_TEMPTABLE":"sample","INPUT_TYPE":"hdfs","INPUT_PATH":"hdfs://x.x.x.x:X/sparkStream/sample1/"},"process":{"query.param":"${http.query.param.name}","PROCESS_SQL":"1","PROCESS_TYPE":"sql"},"attributes":{"path":"./","restlistener.remote.source.host":"127.0.0.1","filename":"1211999192960535","restlistener.remote.user.dn":"none","uuid":"2b025f49-7d53-49db-8063-24ddda29fc4a"}}

无法将数据pickle或转换为JSON之类的序列化格式,因为它来自当前格式的另一个进程。你知道吗


Tags: pathinputoutput字典remoteparamtypehdfs
1条回答
网友
1楼 · 发布于 2024-06-17 12:58:32

如果没有re,这可能更有效,并且有一些假设:

  • 字符串总是以'{开头,以}'结尾
  • 顶层元素由,''分隔,数据中没有其他,''
  • 子级元素由,分隔,数据中没有其他,

然后可以这样做:

ms = "'{output:{OUTPUT_PATH:hdfs://x.x.x.x:X/tmp/x/x,OUTPUT_TYPE:hdfs},''input:{INPUT_TEMPTABLE:sample,INPUT_TYPE:hdfs,INPUT_PATH:hdfs://x.x.x.x:X/sparkStream/sample1/},''process:{query.param:${http.query.param.name},PROCESS_SQL:1,PROCESS_TYPE:sql},''attributes:{path:./,restlistener.remote.source.host:127.0.0.1,filename:1211999192960535,restlistener.remote.user.dn:none,uuid:2b025f49-7d53-49db-8063-24ddda29fc4a}}'"
result = {}
# get rid of '{ and '}
# split on ,''
for e in ms[2:-2].split(",''"):
    # e is top level
    # split on {
    # e[0] is toplevel key
    # e[1] is sublevel
    e = e.split('{',1)
    # p is sublevel
    # if multiple sublevels split on ,
    p = e[1].split(',') if ',' in e[1] else [e[1]]
    i_dict = {}
    for v in p:
        # for each value in p get rid of trailing }
        v = v.rstrip('}')
        # split the value
        # i[0] is sublevel key
        # i[1] is sublevel value
        i = v.split(':',1)
        #add to sublevel dict
        i_dict[i[0]] = i[1]
    #add sublevel dict as value for toplevel
    result[e[0][:-1]] = i_dict
print(result)

输出是字典:

{'output': {'OUTPUT_PATH': 'hdfs://x.x.x.x:X/tmp/x/x', 'OUTPUT_TYPE': 'hdfs'}, 'input': {'INPUT_TEMPTABLE': 'sample', 'INPUT_TYPE': 'hdfs', 'INPUT_PATH': 'hdfs://x.x.x.x:X/sparkStream/sample1/'}, 'process': {'query.param': '${http.query.param.name', 'PROCESS_SQL': '1', 'PROCESS_TYPE': 'sql'}, 'attributes': {'path': './', 'restlistener.remote.source.host': '127.0.0.1', 'filename': '1211999192960535', 'restlistener.remote.user.dn': 'none', 'uuid': '2b025f49-7d53-49db-8063-24ddda29fc4a'}}

由于没有其他的输入字符串,这段代码没有进一步的测试,YMMV。你知道吗

相关问题 更多 >