是否可以转换字典的字符串表示形式,其中键未用双引号括起来,例如
'{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"}}
数据无法被腌制或转换为像JSON这样的序列化格式,因为它来自当前格式的另一个进程。
答案 0 :(得分:2)
没有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。