如何用Python修改JSON对象内的一个字符串,并将其转换为另一个JSON对象,从而增加一个键值?

0 人关注

我想找到一种方法,利用Python将我的JSON对象中的一个字符串转换成另一个JSON对象(嵌套),从而为我的字符串中的值添加一个键,这些值是用""分隔的。 ; ".

My current JSON object:

"reference": "#############", "messageContext": "", "from": { "number": "+#############", "name": "" "to": { "number": "#############" "message": { "text": "12302;8;6245;d517666e-41ca-459a-9b35-c49386df537b;2;2;50.8447;-4.3614;2021-04-28T22:24:12.204Z;rec123;PRD", "media": { "mediaUri": "", "contentType": "", "title": "" "custom": {} "groupings": [ "time": "2021-05-02 14:03:22", "timeUtc": "2021-05-02T12:03:22", "channel": "Sms"

我想拥有的格式是这样的,我将把文本改为对象,同时增加关键值。

我试图获得的结果是 (Inside of text:" " ):

"reference": ""#############",", "messageContext": "", "from": { "number": "+"#############",", "name": "" "to": { "number": ""#############"," "message": { "text": { "APSI": "12302", "idVhl": 8, "idDrv": 6245, "GUID": "d517666e-41ca-459a-9b35-c49386df537b", "idLne": 2, "idSvc": 2, "Lat": 50.8447, "Lon": -4.3614, "Timestamp": "2021-04-28T22:24:12.204Z", "Rec": "rec123", "Env": "PRD" "media": { "mediaUri": "", "contentType": "", "title": "" "custom": {} "groupings": [ "time": "2021-05-02 14:03:22", "timeUtc": "2021-05-02T12:03:22", "channel": "Sms"
3 个评论
你能不能把你试过的东西和你遇到的问题也贴出来?
你好 @CristiFati 我已经尝试了一些东西,我读了一些关于使用json.load来尝试将其格式化为一个对象,并尝试先检索 "text "值,但它一直告诉我 "Result。Failure Exception: keyError: 'text'""
python
json
formatting
PrayingMantis
PrayingMantis
发布于 2021-05-02
1 个回答
AdamMcKay
AdamMcKay
发布于 2021-05-02
已采纳
0 人赞同

给出你的JSON对象为 input ,这个函数将返回你的预期输出。

def transform(input):
    text = input['message']['text']
    text_list = text.split(';')
    text_dict = {
        'APSI': text_list[0],
        'idVhl': int(text_list[1]),
        'idDrv': int(text_list[2]),
        'GUID': text_list[3],
        'idLne': int(text_list[4]),
        'idSvc': int(text_list[5]),
        'Lat': float(text_list[6]),
        'Lon': float(text_list[7]),
        'Timestamp': text_list[8],
        'Rec': text_list[9],
        'Env': text_list[10]