skip to Main Content
#Example COBOL statement 
cobol_statement = "MODIFY MAP CURSOR AT NBS-DS-01(1) FOR FIELD (NBS-DS-01, NBS-DS-02(2), NBS-DS-03(3))"

I need a json structure to covert this COBOL i need a result as

{"cursor": "NBS-DS-01(1)", "for": ["NBS-DS-01","NBS-DS-02(2)","NBS-DS-03(3)"]}

I need the json structure to be dynamic whatever the field I’am adding to be convert automatically

2

Answers


  1. Try something like this:

    import re
    import json
    
    def cobol_to_json(cobol_statement):
        cursor_pattern = r'CURSORs+ATs+([w-]+(d+))'
        for_pattern = r'FORs+FIELDs+((.*?))'
        cursor_match = re.search(cursor_pattern, cobol_statement, re.IGNORECASE)
        for_match = re.search(for_pattern, cobol_statement, re.IGNORECASE)
        if cursor_match and for_match:
            cursor = cursor_match.group(1)
            fields = [field.strip() for field in for_match.group(1).split(',')]
            result = {"cursor": cursor, "for": fields}
            return json.dumps(result, indent=4)
        else:
            return None
    
    
    cobol_statement = "MODIFY MAP CURSOR AT NBS-DS-01(1) FOR FIELD (NBS-DS-01, NBS-DS-02(2), NBS-DS-03(3))"
    json_result = cobol_to_json(cobol_statement)
    if json_result:
        print(json_result)
    else:
        print("Failed to parse COBOL statement.")
    

    Output:

    {
        "cursor": "NBS-DS-01(1)",
        "for": [
            "NBS-DS-01",
            "NBS-DS-02(2"
        ]
    }
    
    Login or Signup to reply.
  2. You can try this regular expression. If you use a different format you need to reconstruct the regex.

    import re
    import json
    
    def cobol_to_json(statement):
        pattern = r"MODIFY MAP CURSOR AT ([w-]+(d+)) FOR FIELD (([w-]+(?:(d+))?(?:, [w-]+(?:(d+))?)*))"
        match = re.match(pattern, statement)
        if match:
            cursor = match.group(1)
            fields_str = match.group(2)
            fields = [field.strip() for field in fields_str.split(',')]
            result = {
                "cursor": cursor,
                "for": fields
            }
            return json.dumps(result, indent=4)
        else:
            return "invalid statement"
    
    
    statement = "MODIFY MAP CURSOR AT NBS-DS-01(1) FOR FIELD (NBS-DS-01, NBS-DS-02(2), NBS-DS-03(3))"
    result = cobol_to_json(statement)
    print(result)
    

    Output:

    {
        "cursor": "NBS-DS-01(1)",
        "for": [
            "NBS-DS-01",
            "NBS-DS-02(2)",
            "NBS-DS-03(3)"
        ]
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search