[Python] Transforming polars Dataframe to Nested JSON Format

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    I have a dataframe that contains a product name, question, and answers. I would like to process the dataframe and transform it into a JSON format. Each product should have nested sections for questions and answers.

    My dataframe:

    import polars as pl

    df = pl.DataFrame({
    "Product": ["X", "X", "Y", "Y"],
    "Question": ["Q1", "Q2", "Q3", "Q4"],
    "Anwers": ["A1", "A2", "A3", "A4"],
    })


    Desired Output:

    {
    "faqByCommunity": {
    "id": 5,
    "communityName": "name",
    "faqList": [
    {
    "id": 1,
    "product": "X",
    "faqs": [
    {
    "id": 1,
    "question": "Q1",
    "answer": "A1"
    },
    {
    "id": 2,
    "question": "Q2",
    "answer": "A2"
    }

    ]
    },
    {
    "id": 2,
    "product": "Y",
    "faqs": [
    {
    "id": 1,
    "question": "Q3",
    "answer": "A3"
    },
    {
    "id": 2,
    "question": "Q4",
    "answer": "A4"
    }

    ]
    }
    ]
    }
    }


    Since the first part it's static , i think i could append it to the file before and after polars writes to it (Like my other question ). However, im not sure how can i work with the nested part

    Continue reading...

Compartilhe esta Página