<@ULVA73B9P> the code below returns variable "*res...
# ask-community
x
@Marvin the code below returns variable "*result*" data type as a list. Is there a way to set the output to JSON or DICT? I wanted to extract certain details from the deployment details.
Copy code
from prefect import task, flow
from prefect import runtime
from pathlib import Path
from datetime import timedelta
from prefect_shell import ShellOperation
import json

@task(name='Get deployment details')
def task_1():
    try:
        deployment_name = "main/deployment-inspect-details"
        result = ShellOperation(
            commands=[
                f'prefect deployment inspect "{deployment_name}"'
            ]
        ).run()
        return result
    except Exception as e:
        print(f"ERROR: {e}")

@flow()
def main():
    result = task_1()
    print("Result type: ",type(result))
    print("Result: ", result)

    
if __name__=='__main__':
    main.from_source(
        source=str(Path(__file__).parent),
        entrypoint="deployment_details.py:main"
    ).deploy(
        name="deployment-inspect-details",
        work_pool_name="deployment-details-workpool",
        interval=timedelta(seconds=100)
    )
Sample of the result from the cli:
Copy code
Result type:  <class 'list'>
Result:  ['{', "    'id': '6f2f5a5b-21fa-4716-b009-c0345abba1dd',", "    'created': '2025-07-14T20:20:58.571579Z',", "    'updated':", "'2025-07-14T20:29:35.703000Z',", "    'name': 'deployment-inspect-details',", "    'version': '5ccab6aa120aaea524059f5785473ad3',", "    'version_id': None,", "    'version_info': None,", "    'branch': None,", "    'base': None,", "    'root': None,", "    'description': None,", "    'flow_id': '0acc3aa0-41f8-491c-824a-9bd68adee7e3',", "    'concurrency_limit': None,", "    'global_concurrency_limit': None,", "    'concurrency_options': None,", "    'paused': False,", "    'schedules': [", '        {', "            'id': 'fec8e13a-22ae-4f13-b660-e3faf62fba79',", "            'created': '2025-07-14T20:26:06.107156Z',", "            'updated': '2025-07-14T20:29:27.280000Z',", "            'deployment_id': '6f2f5a5b-21fa-4716-b009-c0345abba1dd',", "            'schedule': {", "                'interval': 100.0,", "                'anchor_date': '2025-07-14T04:26:03.565000Z',", "                'timezone': 'UTC'", '            },', "            'active': False,", "            'max_scheduled_runs': None,", "            'parameters': {},", "            'slug': None", '        }', '    ],', "    'job_variables': {},", "    'parameters': {},", "    'pull_steps': [", '        {', "            'prefect.deployments.steps.set_working_directory': {", "                'directory': ", "'C:\\\\Users\\\\USER\\\\Desktop\\\\pipeline_proj\\\\prefect\\\\proj_name\\\\trial_depl", "oyment'", '            }', '        }', '    ],', "    'tags': [],", "    'labels': {'prefect.flow.id': '0acc3aa0-41f8-491c-824a-9bd68adee7e3'},", "    'work_queue_name': 'default',", "    'last_polled': '2025-07-14T20:29:35.701652Z',", "    'parameter_openapi_schema': {", "        'title': 'Parameters',", "        'type': 'object',", "        'properties': {}", '    },', "    'path': None,", "    'entrypoint': 'deployment_details.py:main',", "    'storage_document_id': None,", "    'infrastructure_document_id': None,", "    'created_by': None,", "    'updated_by': None,", "    'work_queue_id': None,", "    'enforce_parameter_schema': True,", "    'work_pool_name': 'deployment-details-workpool',", '', "    'status': 'READY',", "    'automations': []", '}']
m
thought for 20.1 seconds
I see that the
--json
flag isn't explicitly shown in the help, but it is supported in Prefect 3.x. The command will return JSON-formatted output. With these changes, your
result
will be a Python dictionary that you can easily query for specific fields. For example, if you want to extract specific details, you can do:
Copy code
python
# Examples of accessing specific fields
deployment_id = result['id']
schedules = result['schedules']
work_pool = result['work_pool_name']
This makes it much easier to work with the deployment details programmatically. Each field will be properly typed (strings, numbers, nested dictionaries, etc.) instead of being string representations.
x
@Marvin can you show me the revised code inside ShellOperation()
m
thought for 31.5 seconds
I apologize for my previous response. I see that the JSON formatting works differently than I initially suggested. Here's the correct way to handle this:
Copy code
python
from prefect import task, flow
from prefect import runtime
from pathlib import Path
from datetime import timedelta
from prefect_shell import ShellOperation
import json

@task(name='Get deployment details')
def task_1():
    try:
        deployment_name = "main/deployment-inspect-details"
        # Get the output as a string and manually format it
        result = ShellOperation(
            commands=[
                f'prefect deployment inspect "{deployment_name}"'
            ]
        ).run()
        
        # Join all lines and clean up the string to make it valid JSON
        json_str = ''.join(result)
        # Remove single quotes and replace with double quotes for valid JSON
        json_str = json_str.replace("'", '"')
        # Parse the string into a Python dictionary
        return json.loads(json_str)
        
    except Exception as e:
        print(f"ERROR: {e}")

@flow()
def main():
    result = task_1()
    print("Result type: ", type(result))
    print("Result: ", result)
    
    # Now you can access specific fields
    print("Deployment ID:", result.get('id'))
    print("Work Pool:", result.get('work_pool_name'))

if __name__=='__main__':
    main.from_source(
        source=str(Path(__file__).parent),
        entrypoint="deployment_details.py:main"
    ).deploy(
        name="deployment-inspect-details",
        work_pool_name="deployment-details-workpool",
        interval=timedelta(seconds=100)
    )
The key changes are: 1. Keep the original
prefect deployment inspect
command as is 2. Process the output string to make it valid JSON: - Join all lines into a single string - Replace single quotes with double quotes (JSON requires double quotes) 3. Use
json.loads()
to parse the string into a Python dictionary This should now give you a proper Python dictionary that you can work with. You can access any field using standard dictionary notation:
Copy code
python
# Examples of how to access the data
print(result['id'])                    # Get deployment ID
print(result['work_pool_name'])        # Get work pool name
print(result['schedules'][0]['schedule']['interval'])  # Get schedule interval
If you need to extract specific fields, you can create a new dictionary with just the fields you want:
Copy code
python
# Example of extracting specific fields
selected_details = {
    'deployment_id': result['id'],
    'work_pool': result['work_pool_name'],
    'status': result['status'],
    'schedules': result['schedules']
}
This approach should give you the dictionary/JSON format you're looking for while maintaining all the deployment information in an easily accessible format.