Python POJO pattern matching – with nested classes

Question:

I’m attempting to implement pattern matching for JSON using POJO classes in Python, similar to how it’s done in Scala. Could you please suggest the best approach for achieving this?

import json
from dataclasses import dataclass


class GradeDetails:
    first_term: str
    second_term: str
    pass_or_fail: str


class SubjectDetails:
    subject_name: str
    term_score: GradeDetails


@dataclass
class Student:
    name: str
    roll_number: str
    grade_class: str
    subjects: SubjectDetails


def json_to_json_string():
    json_data = '''
    {
      "name": "John Doe",
      "roll_number": "123456",
      "grade_class": "10th Grade",
      "subjects": 
        {
          "subject_name": "Math",
          "term_score": {
            "first_term": "A",
            "second_term": "B",
            "pass_or_fail": "Pass"
          }
        }
      
    }
    '''
    parsed_data = json.loads(json_data)
    return parsed_data


if __name__ == '__main__':
    data_dict = json_to_json_string()
    student_data = Student(**data_dict)
    student_subject = student_data.subjects

    print(f" student data :: n {student_data} n")
    print(f" subject details are :: n {student_subject.subject_name} n")

While printing subject details I am getting the error AttributeError: 'dict' object has no attribute 'subject_name'. What am I doing wrong?

Asked By: Sarkuna

||

Answers:

class DictParser:

    @classmethod
    def object_mapper(cls, dict):
        parsed_object = cls()
        parsed_object.__dict__.update(dict)
        return parsed_object

python_object= json.loads(json_string, object_hook=DictParser.object_mapper)

The object_mapper method in the DictParser class demonstrates a custom object mapping function used as an object_hook in the json.loads() function. It creates an instance of the DictParser class and populates its attributes based on the key-value pairs from the dictionary.

Answered By: Sarkuna
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.