【问题标题】:how to merge two json data by mapping如何通过映射合并两个json数据
【发布时间】:2022-12-14 04:59:14
【问题描述】:

我有两个 json 数据作为

json_1 = [{'purchasedPerson__id': 2, 'credit': 3000}, {'purchasedPerson__id': 4, 'credit': 5000}]
json_2 = [{'purchasedPerson__id': 1, 'debit': 8526}, {'purchasedPerson__id': 4, 'debit': 2000}]

我想将 json 和所需的输出合并为

json_final = [{'purchasedPerson__id': 2, 'credit': 3000 , 'debit'=0}, 
{'purchasedPerson__id': 4, 'credit': 5000 , 'debit'=2000},
 {'purchasedPerson__id': 1, 'credit'=0, 'debit': 8526}]

如何完成上述方法

【问题讨论】:

    标签: python json


    【解决方案1】:
    json_1 = [{'purchasedPerson__id': 2, 'credit': 3000}, {'purchasedPerson__id': 4, 'credit': 5000}]
    json_2 = [{'purchasedPerson__id': 1, 'debit': 8526}, {'purchasedPerson__id': 4, 'debit': 2000}]
    
    # create a dictionary for the merged data
    data = {}
    
    # loop through each JSON and add the data to the dictionary
    for j in json_1:
        data[j['purchasedPerson__id']] = {'credit': j['credit'], 'debit': 0}
    
    for j in json_2:
        if j['purchasedPerson__id'] in data:
            data[j['purchasedPerson__id']] = {'credit': data[j['purchasedPerson__id']]['credit'], 'debit': j['debit']}
        else:
            data[j['purchasedPerson__id']] = {'credit': 0, 'debit': j['debit']}
    
    # convert the dictionary to a list
    json_final = []
    for key, value in data.items():
        json_final.append({'purchasedPerson__id': key, 'credit': value['credit'], 'debit': value['debit']})
    
    print(json_final)
    

    【讨论】:

      【解决方案2】:

      这是pandas可以非常方便的情况。通过转换为数据帧并合并到“purchasedPerson__id”,您将获得所需的输出:

      import pandas as pd
      
      json_1 = [{'purchasedPerson__id': 2, 'credit': 3000}, {'purchasedPerson__id': 4, 'credit': 5000}]
      json_2 = [{'purchasedPerson__id': 1, 'debit': 8526}, {'purchasedPerson__id': 4, 'debit': 2000}]
      df1 = pd.DataFrame(json_1)
      df2 = pd.DataFrame(json_2)
      
      df_out = pd.merge(df1, df2, on="purchasedPerson__id", how="outer").fillna(0)
      df_out.to_dict(orient="records")
      

      输出:

      [{'purchasedPerson__id': 2, 'credit': 3000.0, 'debit': 0.0}, {'purchasedPerson__id': 4, 'credit': 5000.0, 'debit': 2000.0}, {'purchasedPerson__id': 1, 'credit': 0.0, 'debit': 8526.0}]
      

      【讨论】:

      • 我写了几个步骤,这样你就可以一路打印每一个,但它基本上适合一行:pd.merge(pd.DataFrame(json_1), pd.DataFrame(json_2), on="purchasedPerson__id", how="outer").fillna(0).to_dict(orient="records")
      【解决方案3】:
      # Initialize the final JSON array
      json_final = []
      
      # Loop through the first JSON data set
      for item in json_1:
          # Initialize the final JSON object for this item
          final_item = {'purchasedPerson__id': item['purchasedPerson__id'], 'credit': item['credit'], 'debit': 0}
          # Loop through the second JSON data set
          for item2 in json_2:
              # If the id matches, update the final item with the debit value
              if item['purchasedPerson__id'] == item2['purchasedPerson__id']:
                  final_item['debit'] = item2['debit']
          # Add the final item to the final JSON array
          json_final.append(final_item)
      
      # Loop through the second JSON data set
      for item in json_2:
          # Initialize a flag to keep track of whether the item already exists in the final JSON array
          exists = False
          # Loop through the final JSON array
          for final_item in json_final:
              # If the id matches, set the exists flag to True
              if final_item['purchasedPerson__id'] == item['purchasedPerson__id']:
                  exists = True
          # If the item does not exist in the final JSON array, add it with credit and debit values of 0
          if not exists:
              json_final.append({'purchasedPerson__id': item['purchasedPerson__id'], 'credit': 0, 'debit': item['debit']})
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-08
        • 2020-04-12
        • 2018-05-25
        • 1970-01-01
        • 2023-03-16
        • 2016-06-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多