亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用python將自定義字符串轉換為json?

如何使用python將自定義字符串轉換為json?

慕的地6264312 2023-02-07 11:04:49
我有一個如下所示的字符串:'a:b# c:d# e:f#'how to convert this into json like = {'a':'b','c':'d','e':'f'}using python. 任何幫助表示贊賞。TIA。
查看完整描述

4 回答

?
慕妹3242003

TA貢獻1824條經驗 獲得超6個贊

您可以使用re.findall獲取所有匹配值對,然后將該列表轉換為dict:


import re


s = '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 json

print(json.dumps(d))

輸出:


{"a": "b", "c": "d", "e": "f"}


查看完整回答
反對 回復 2023-02-07
?
Helenr

TA貢獻1780條經驗 獲得超4個贊

刪除#,然后在空間上拆分以獲得零件,然后拆分:以配對映射


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'}


查看完整回答
反對 回復 2023-02-07
?
回首憶惘然

TA貢獻1847條經驗 獲得超11個贊

這不是最快/最短的解決方案。但是我認為它可能是最容易被初學者理解的。


然后,您可以根據需要縮短/優化代碼。


你的問題由兩部分組成。


1.) 如何將特定格式的字符串轉換為 python 數據結構


2.) 如何將 python 數據結構轉換為 json


import json


def 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 result


example_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 file

with(open("myjsonfile.json", "w")) as fout:

    json.dump(rslt_dict, fout)


查看完整回答
反對 回復 2023-02-07
?
躍然一笑

TA貢獻1826條經驗 獲得超6個贊

import re

import json


str = 'a:b# c:d# e:f#'        # input string

kv = re.compile("(\w):(\w)")  # prepare regular expression

l = kv.findall(str)           # find all <key>:<value> pairs

d = dict(l)                   # convert list to dict

j = json.dumps(d)             # generate JSON

print( d )

印刷


{'a': 'b', 'c': 'd', 'e': 'f'}


查看完整回答
反對 回復 2023-02-07
  • 4 回答
  • 0 關注
  • 182 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號