【问题标题】:convert json from one form to another in python在python中将json从一种形式转换为另一种形式
【发布时间】:2020-11-21 06:34:57
【问题描述】:

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

{
 "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 中像上面那样合并日志?

【问题讨论】:

  • 这是你吗? stackoverflow.com/questions/63188028/…你有多个账号吗?
  • 那是我的项目合作伙伴
  • 好吧,好吧...我的回答不应该像你一样产生响应,除非它被滥用了。
  • 不过,您并没有指定如何处理计数;应该将列表连接起来,还是将计数相加?
  • 只是串联

标签: python json python-3.x django list


【解决方案1】:

response = [
    {
        "timestamp": "21:15-21:30",
        "logs": [{"exception": "IllegalAgrumentsException", "count": 1}],
    },
    {
        "timestamp": "21:15-21:30",
        "logs": [{"exception": "NullPointerException", "count": 2}],
    },
]
final = []
for k,v in groupby(response, lambda x:x.pop('timestamp')):
    final.append({
        'timestamp':k,
        'logs':reduce(
        lambda x,y:  {'logs':y['logs']+x['logs']},      
        [*v]
        )['logs']
    })
print(final)
Output 
[
    {
        "timestamp": "21:15-21:30",
        "logs": [
            {"exception": "IllegalAgrumentsException", "count": 1},
            {"exception": "NullPointerException", "count": 2},
        ],
    }
]
    

【讨论】:

    【解决方案2】:

    other part of this question 一样,它是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},
            ],
        }
    ]
    

    【讨论】:

    • list indices must be integers or slices, not strfor datum.. 行错误
    • 不,该错误并非来自此代码。如果您的列表仍在 "response": [...] 中,您自然必须先打开它:input_data = response["response"] 或诸如此类。
    • 是的,我看到了。但是我的数据顺序完全改变了。我希望我的输出数据顺序保持相同的输入数据
    • 改用OrderedDict
    【解决方案3】:

    考虑你的情况..

    查看下面的补丁

    _dict = {
        "response": [
            {
                "timestamp": "21:15-21:30",
                "logs": [
                    {
                        "exception": "IllegalAgrumentsException",
                        "count": 1
                    }
                ]
            },
            {
                "timestamp": "21:15-21:30",
                "logs": [
                    {
                        "exception": "NullPointerException",
                        "count": 2
                    }
                ]
            }]}
    
    _final = {}
    for _dict in _dict.get('response'):
        if not _dict.get('timestamp') in _final:
            _final[_dict.get('timestamp')] = {
                'timestamp': _dict.get('timestamp'),
                'logs': []
            }
        _final[_dict.get('timestamp')]['logs'] += _dict.get('logs')
    
    _result ={'response': list(_final.values())}
    
    print(_result)
    

    将打印...

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

    【讨论】:

    • 我的回复是一个列表而不是字典
    • 因为您的响应是一个列表...替换: _result ={'response': list(_final.values())} 与 _result = list(_final.values())
    猜你喜欢
    • 2015-01-26
    • 1970-01-01
    • 2015-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 2016-11-25
    相关资源
    最近更新 更多