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

编写Python脚本实现字典从Python文件到JSON文件的格式转换

Got it, let's tackle this problem step by step. You need a Python script that parses the variables method from your abc.py file, transforms the variable definitions into your target JSON structure, and writes it to abc.json. Here's a robust way to do this using Python's AST module (to safely parse code instead of error-prone regex) and careful string handling to match your exact format requirements:

Solution Script

import ast
import json

def generate_target_json():
    # Step 1: Read and parse the abc.py file to extract variables_list
    with open('abc.py', 'r') as py_file:
        py_content = py_file.read()

    # Parse Python code into an Abstract Syntax Tree (AST)
    tree = ast.parse(py_content)
    variables_list = None

    # Traverse the AST to find the variables method and its variables_list assignment
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef) and node.name == 'variables':
            for stmt in node.body:
                if isinstance(stmt, ast.Assign):
                    for target in stmt.targets:
                        if (isinstance(target, ast.Attribute) 
                            and target.attr == 'variables_list'):
                            # Safely evaluate the list definition (using dummy namespace to avoid errors)
                            dummy_namespace = {'output_analysis': {}}
                            variables_list = eval(
                                compile(ast.Expression(stmt.value), '', 'eval'),
                                {}, 
                                dummy_namespace
                            )
                            break
                    if variables_list:
                        break
            break

    if not variables_list:
        raise ValueError("Failed to locate self.variables_list in abc.py's variables method")

    # Step 2: Transform each variable entry to match the target format
    transformed_vars = []
    for var in variables_list:
        # Fix description: swap double quotes around output_analysis keys to single quotes
        raw_desc = var['description']
        formatted_desc = raw_desc.replace('output_analysis["', "output_analysis['").replace('"]', "']")
        # Wrap description in double quotes (including f-string prefix if present)
        quoted_desc = f'"{formatted_desc}"'

        # Build datatype and value as quoted expression strings
        datatype_expr = f'type(output_analysis[\'{var["name"]}\']).__name__'
        quoted_datatype = f'"{datatype_expr}"'

        value_expr = f'output_analysis[\'{var["name"]}\']'
        quoted_value = f'"{value_expr}"'

        # Assemble the transformed variable object
        transformed_vars.append({
            "name": f'"{var["name"]}"',
            "description": quoted_desc,
            "datatype": quoted_datatype,
            "value": quoted_value
        })

    # Step 3: Construct the full target JSON string (to preserve exact quote formatting)
    base_json = '''{
    "truth_table": {
        "business_logic": {
            "department": { "name": "default" },
            "domain": { "name": "default" },
            "variables": [
    '''

    # Add each transformed variable with proper indentation
    for idx, var in enumerate(transformed_vars):
        var_str = f'''                {{
                    "name": {var["name"]},
                    "description": {var["description"]},
                    "datatype": {var["datatype"]},
                    "value": {var["value"]}
                }}'''
        if idx != len(transformed_vars) - 1:
            var_str += ','
        base_json += '\n' + var_str

    base_json += '''
            ]
        }
    }
}'''

    # Step 4: Write the final JSON to abc.json
    with open('abc.json', 'w') as json_file:
        json_file.write(base_json)

    print("abc.json generated successfully!")

if __name__ == "__main__":
    generate_target_json()

How It Works

  1. AST Parsing: We use Python's built-in ast module to safely extract the self.variables_list definition from abc.py. This avoids the pitfalls of regex parsing (like mistaking strings for code syntax).
  2. Format Transformation:
    • Adjusts the description field to replace double quotes around output_analysis keys with single quotes, then wraps the entire description in double quotes.
    • Reconstructs datatype and value as string representations of the original Python expressions, ensuring the correct quote style for output_analysis keys.
    • Removes the scenario field entirely since it's not part of your target format.
  3. JSON Construction: Instead of relying on json.dumps (which would escape inner quotes), we build the JSON string manually to match your exact example formatting.

Usage

  • Place this script in the same directory as abc.py.
  • Run the script, and it will generate abc.json matching your required structure.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 10:12:50