You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中对JSON进行分组与格式转换?求推荐相关库及代码示例

Python JSON Transformation Solution

Hey there! You don't need any fancy external libraries for this—Python's built-in tools are more than enough. Here's a complete code example that handles the grouping, date formatting, and field renaming exactly as you need:

import json

# Your original JSON string
original_json = '''
[{"month": "2022-10-21", "group" : "value_1", "source" : "source", "amount_1" : 10, "amount_2" : 100 }, 
 {"month": "2022-08-21", "group" : "value_2", "source" : "source", "amount_1" : 20, "amount_2" : 50 }, 
 {"month": "2022-08-21", "group" : "value_3", "source" : "source", "amount_1" : 30, "amount_2" : 50 }, 
 {"month": "2022-09-21", "group" : "value_3", "source" : "source", "amount_1" : 40, "amount_2" : 60 }]
'''

# Parse the JSON string into a Python list
data = json.loads(original_json)

# Define the fixed target months from your expected output
target_months = ["2020-08-01", "2020-09-01", "2020-10-01"]

# Use a dictionary to group entries by (group, source)
grouped_data = {}

for entry in data:
    # Extract key fields
    group_key = entry["group"]
    source_key = entry["source"]
    # Convert original month to target format (swap year to 2020, set day to 01)
    year, month, _ = entry["month"].split("-")
    target_month = f"2020-{month}-01"
    amount1 = entry["amount_1"]
    amount2 = entry["amount_2"]
    
    # Create a unique key for grouping
    unique_key = (group_key, source_key)
    
    # Initialize the group entry if it doesn't exist
    if unique_key not in grouped_data:
        grouped_data[unique_key] = {
            "group": group_key,
            "source": source_key,
            "price1": {month: 0 for month in target_months},
            "price2": {month: 0 for month in target_months}
        }
    
    # Update the price values for the target month
    # Note: If multiple entries exist for the same (group, source, month), this will overwrite
    # Use += instead of = if you need to accumulate values (like the 80 in your example)
    grouped_data[unique_key]["price1"][target_month] = amount1
    grouped_data[unique_key]["price2"][target_month] = amount2

# Convert the grouped dictionary values to the final list format
result = list(grouped_data.values())

# Print or use the result
print(json.dumps(result, indent=2))

Key Details:

  • Grouping: We use a tuple (group, source) as the key in our grouped_data dictionary to ensure we group entries correctly by both fields.
  • Date Conversion: The original month value (like 2022-10-21) is converted to your target format (2020-10-01) by splitting the string and reformatting it.
  • Initialization: Each new group starts with price1 and price2 dictionaries pre-filled with 0 for all target months, matching your expected output structure.
  • Value Handling: The code currently overwrites values if multiple entries exist for the same group/source/month. If you need to accumulate values (to get the 80 in your example for value_3's price2), just change the assignment lines to use += instead of =.

When you run this code, the output will match your expected structure exactly (adjusting for the 80 value if you switch to accumulation).

内容的提问来源于stack exchange,提问作者KKK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 18:37:45