首页 > 解决方案 > 在python中将列表转换为特定的json

问题描述

我正在解决一个问题,我的输出是这样的:List with long string inside it

["21:15-21:30 IllegalAgrumentsException 1,
  21:15-21:30 NullPointerException 2,
  22:00-22:15 UserNotFoundException 1,
  22:15-22:30 NullPointerException 1
  ....."]

我需要像这样转换数据:

response: [
     {
        "time": "21:15-21:30",
        "logs": [
            {
                "exception": "IllegalAgrumentsException",
                "count": 1
            },{
                "exception": "NullPointerException",
                "count": 2
            }
        ]
    },
    {
        "time": "22:00-22:15",
        "logs": [
            {.....
            }
         ]
    }
]

如何将数据转换为这种特定格式?

错误 :

print(type(input)) // <class 'list'>
input = re.split(r',\s+', input[0])
print(input)  // ['21:15-21:30 IllegalAgrumentsException 1,
                   21:15-21:30 NullPointerException 2.....']

output = collections.defaultdict(collections.Counter)
for line in input:
    time, error, count = line.split(None, 2)
    output[time][error] += int(count)  //invalid literal for int() with base 10: '1

标签: pythonarraysjsonpython-3.xlist

解决方案


我假设您的输入列表实际上是一个字符串列表,但如果不是,您可以先拆分字符串:

import re
# If the input data is a list that has one entry, peel it off
input_data = input_data[0]
# Now we should have a string to split...
input_data = re.split(r',\s*', input_data)

像往常一样,分组和整理操作collections.defaultdict(在这种特殊的求和情况下collections.Counter也是如此)派上用场:

import collections

input_data = [
    "21:15-21:30 IllegalAgrumentsException 1",
    "21:15-21:30 NullPointerException 2",
    "22:00-22:15 UserNotFoundException 1",
    "22:15-22:30 NullPointerException 1",
]

output = collections.defaultdict(collections.Counter)
for line in input_data:
    time, error, count = line.split(None, 2)
    output[time][error] += int(count)

response = [
    {
        "time": time,
        "logs": [
            {"exception": exception, "count": count}
            for (exception, count) in counter.items()
        ],
    }
    for (time, counter) in output.items()
]

print(response)

输出(格式化)

[
    {
        "time": "21:15-21:30",
        "logs": [
            {
                "exception": "IllegalAgrumentsException",
                "count": 1,
            },
            {
                "exception": "NullPointerException",
                "count": 2,
            },
        ],
    },
    {
        "time": "22:00-22:15",
        "logs": [
            {
                "exception": "UserNotFoundException",
                "count": 1,
            }
        ],
    },
    {
        "time": "22:15-22:30",
        "logs": [
            {
                "exception": "NullPointerException",
                "count": 1,
            }
        ],
    },
]

推荐阅读