首页 > 解决方案 > 使用通用条目合并 json 数组

问题描述

我有一个 python 脚本,它使用 Get API 给我两个 json 数组

数据1

{'result': [
    {'number': '0010041', 'month': 'January'}, 
    {'number': '0010042', 'month': 'March'}
    ]}

数据2

{'result': [
    {'task': '0010041', 'time_left': '20 sec'}, 
    {'task': '0010042', 'time_left': '6 min'}
    ]}

我想使用公共条目合并两者,因此在这种情况下,它们相同的“数字”和“任务”合并数组中的其余数据。

例如。

'number': '0010041', 'month': 'January', 'time_left': '20 sec'
'number': '0010042', 'month': 'March', 'time_left': '6 min'

如何?

标签: pythonarraysjsonmerge

解决方案


这是使用pandas库的一种方式:

import pandas as pd
from pandas.io.json import json_normalize

d1 = json_normalize(d1['result'])
d2 = json_normalize(d2['result'])

# merge the data
lst = d1.merge(d2, left_on='number', right_on='task').drop('task', axis=1)

# converting time to same units (seconds)
lst['time_secs'] = lst['time_left'].str.split().apply(lambda x: int(x[0])*60 if 'min' in x else int(x[0]))

# sort, select cols and convert to dictionary
lst = lst.sort_values('time_secs', ascending=True)[['number','month','time_left']].to_dict(orient='records')

[{'number': '0010041', 'month': 'January', 'time_left': '20 sec'},
 {'number': '0010042', 'month': 'March', 'time_left': '6 min'}]

推荐阅读