首页 > 解决方案 > 在python中将json从一种形式转换为另一种形式

问题描述

我在更改列表后收到了回复。我的回复看起来像这样:

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

我希望结果是这样的: -

 "response": [
     {
       "timestamp": "21:15-21:30",
       "logs": [
          {
              "exception": "IllegalAgrumentsException",
              "count": 1
          },
          {
              "exception": "NullPointerException",
              "count": 2
          } ]
   }

如何在 python 中像上面那样将日志合并在一起?

标签: pythonjsonpython-3.xdjangolist

解决方案


这个问题的其他部分一样,这将是defaultdict时间......但我们需要OrderedDict在这里保持原始时间戳顺序。

import collections

input_data = [
    {
        "timestamp": "21:15-21:30",
        "logs": [{"exception": "IllegalAgrumentsException", "count": 1}],
    },
    {
        "timestamp": "21:15-21:30",
        "logs": [{"exception": "NullPointerException", "count": 2}],
    },
]

logs_by_timestamp = collections.OrderedDict()

for datum in input_data:
    logs_by_timestamp.setdefault(datum["timestamp"], []).extend(datum["logs"])

output_data = [
    {"timestamp": timestamp, "logs": logs}
    for (timestamp, logs) in logs_by_timestamp.items()
]

print(output_data)

输出(格式化)

[
    {
        "timestamp": "21:15-21:30",
        "logs": [
            {"exception": "IllegalAgrumentsException", "count": 1},
            {"exception": "NullPointerException", "count": 2},
        ],
    }
]

推荐阅读