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

2024-09-29 23:20:52 发布

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

我想找到一种方法,使用Python将JSON对象中的字符串转换为另一个JSON对象(嵌套),从而为字符串中使用“”分隔的值添加一个键

我当前的JSON对象:

   {
    "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"
   }

我尝试使用的格式是这样的,在添加键值的同时将文本更改为对象

我试图获得的结果(在文本中):

   {
   "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"
}

Tags: to对象字符串textnamefromjsonnumber
1条回答
网友
1楼 · 发布于 2024-09-29 23:20:52

将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]
    }
    input['message']['text'] = text_dict
    return input

这是通过在;字符上拆分text来完成的,该字符返回所需的所有值的列表。然后,您可以将列表解析为字典,然后将该字典分配给原始的text

相关问题 更多 >

    热门问题