[Python] How to use json_normalize to parse json [closed]

Discussão em 'Python' iniciado por Stack, Janeiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    Here is my json file looks like:

    data = [
    {"Ver":0,
    "Num":[
    {"0":{"A":1,"color": "red", "C": 9,"date": "2024-12-28"}},
    {"1":{"A":5,"color": "blue", "C": 9,"date": "2024-12-29"}},
    {"2":{"A":8,"color": "white","C": 9,"date": "2024-12-30"}}
    ]}
    ]


    I tried to use json_normalize as below:

    0.A 0.color 0.C 0.date 1.A 1.color 1.C 1.date 2.A 2.color \
    0 1.0 red 9.0 2024-12-28 NaN NaN NaN NaN NaN NaN
    1 NaN NaN NaN NaN 5.0 blue 9.0 2024-12-29 NaN NaN
    2 NaN NaN NaN NaN NaN NaN NaN NaN 8.0 white

    2.C 2.date
    0 NaN NaN
    1 NaN NaN
    2 9.0 2024-12-30


    Expected result

    Num A color C date
    0 1 red 9 2024-12-28
    1 5 blue 9 2024-12-29
    2 5 white 9 2024-12-30


    How do I use it? thanks

    if data[] info change to color.json

    {"Ver":0,
    "Num":[
    {"0":{"A":1,"color": "red", "C": 9,"date": "2024-12-28"}},
    {"1":{"A":5,"color": "blue", "C": 9,"date": "2024-12-29"}},
    {"2":{"A":8,"color": "white","C": 9,"date": "2024-12-30"}}
    }


    It give me an error

    import json
    import pandas as pd

    with open('test\\color.json', 'r') as file:
    data = json.load(file)
    #print(data)
    flattened_data = []
    for index, item in enumerate(data[0]['Num']):
    for key, value in item.items():
    flattened_data.append({'Num': int(key), **value})

    # Convert to a DataFrame
    df = pd.DataFrame(flattened_data)


    How can I modify it?

    Continue reading...

Compartilhe esta Página