如何使用python将自定义字符串转换为json?

我有一个如下所示的字符串:'a:b# c:d# e:f#'how to convert this into json like = {'a':'b','c':'d','e':'f'}using python. 任何帮助表示赞赏。TIA。



慕的地6264312
浏览 265回答 4
4回答

慕妹3242003

您可以使用re.findall获取所有匹配值对,然后将该列表转换为dict:import res = 'a:b# c:d# e:f#'d = dict(re.findall(r'(\w+):(\w+)#', s))print(d)输出:{'a': 'b', 'c': 'd', 'e': 'f'}要将其转换为 JSON 字符串,请使用json.dumps:import jsonprint(json.dumps(d))输出:{"a": "b", "c": "d", "e": "f"}

Helenr

删除#,然后在空间上拆分以获得零件,然后拆分:以配对映射s = 'a:b# c:d# e:f#'     res = dict(v.split(':') for v in s.replace("#", "").split())print(res)  # {'a': 'b', 'c': 'd', 'e': 'f'}

回首忆惘然

这不是最快/最短的解决方案。但是我认为它可能是最容易被初学者理解的。然后,您可以根据需要缩短/优化代码。你的问题由两部分组成。1.) 如何将特定格式的字符串转换为 python 数据结构2.) 如何将 python 数据结构转换为 jsonimport jsondef my_parse(data_str):    result = {}    entries = data_str.split('#')  # split input by '#'    for entry in entries:        entry = entry.strip()  # remove leading and trailing white space        if entry:  #            key, val = entry.split(":")            # cleanup key and val. (strip off spaces) perhaps you don't need this            key = key.strip()            val = val.strip()            result[key] = val  # add to our dict    return resultexample_data = 'a:b# c:d# e:f#'rslt_dict = my_parse(example_data)print("result dict is", rslt_dict)# convert to json string.json_str = json.dumps(rslt_dict)# or directly write json to filewith(open("myjsonfile.json", "w")) as fout:    json.dump(rslt_dict, fout)

跃然一笑

import reimport jsonstr = 'a:b# c:d# e:f#'&nbsp; &nbsp; &nbsp; &nbsp; # input stringkv = re.compile("(\w):(\w)")&nbsp; # prepare regular expressionl = kv.findall(str)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# find all <key>:<value> pairsd = dict(l)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# convert list to dictj = json.dumps(d)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# generate JSONprint( d )印刷{'a': 'b', 'c': 'd', 'e': 'f'}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python