将字符串中的 json 转换为 json 格式

时间:2021-07-14 04:06:48

标签: python json

四组数据转换为不同格式的json 1-2=3.4=0 6-7=8=0 10-11=12=13 14-15=16=0

`1-2=3.4=0`  `6-7=8=0`    `10-11=12=13`
a:, "1-2"    a:,"6-7"     a:,"10-11" 
b:, "3.4"    b:,"8"       b:,"12"
c:, "0"      c:,"0"       c:,"13"

原始数据

x = {'OUT': '091309@@@;1-2=3.4=0;6-7=8=0;10-11=12=13;14-15=16=0'}

python 代码

import json
x = json.dumps(x)
tmp = json.loads(x)
print(tmp.keys())

检索密钥

tmp['OUT']

'091309@@@;1-2=3.4=0;6-7=8=0;10-11=12=13;14-15=16=0'

预期结果

x = {'OUT':"091309@@@{'a': '1-2','b': '3.4','c': '0'},{'a': '6-7','b': '8','c': '0'},{'a': '10-11','b': '12','c': '13'},{'a': '14-15','b': '16','c': '0'}"}

2 个答案:

答案 0 :(得分:1)

IIUC,这是将原始数据转换为预期结果的一种方法:

x['OUT'] = x['OUT'].split(';')[0] + ','.join(
    str(dict(zip(['a', 'b', 'c'], i.split('=')))) for i in x['OUT'].split(';')[1:])

答案 1 :(得分:1)

试试regex

import re
import json

x = {'OUT': '091309@@@;1-2=3.4=0;6-7=8=0;10-11=12=13;14-15=16=0'}

parsed_data = re.findall(r'([\d.]+-[\d.]+)=([\d.]+)=([\d.]+)', x['OUT'])

x['OUT'] = x['OUT'].split(';')[0] + ','.join(str(dict(zip(['a', 'b', 'c'], i))) for i in parsed_data)

x
{'OUT': "091309@@@{'a': '1-2', 'b': '3.4', 'c': '0'},{'a': '6-7', 'b': '8', 'c': '0'},{'a': '10-11', 'b': '12', 'c': '13'},{'a': '14-15', 'b': '16', 'c': '0'}"}

找到的正则表达式的详细信息 here