pythontype-conversion

Parsing bytes data in Python


I get this **bytes ** data from API:

b'{"response":{"result":
    [{"date":"2024-09-04T00:00:00","id":1260546,"price":121.51},
     {"date":"2024-09-05T00:00:00","id":1260546,"price":121.54},
     {"date":"2024-09-08T00:00:00","id":1260546,"price":121.55}
    ],"total":3}}'

I need to extract the inner result data (date, id, price), preferably to pandas DataFrame.

Any elegant way to do it?


Solution

    1. Decide the Byte String: Convert the byte string to a regular string.
    2. Partse the Json Data: use Python's json library to parse the JSOn data from the string.
    3. Extract Data and Create DataFrame: Extract the data from the parsed JSOn and use pandas to create a DataFrame.

    I gave you the complete code to do this.

    import json
    import pandas as pd
    
    # Byte string data
    byte_data = b'{"response":{"result":[{"date":"2024-09-04T00:00:00","id":1260546,"price":121.51},{"date":"2024-09-05T00:00:00","id":1260546,"price":121.54},{"date":"2024-09-08T00:00:00","id":1260546,"price":121.55}],"total":3}}'
    
    # Decode byte string to regular string
    json_str = byte_data.decode('utf-8')
    
    # Parse the Json data
    data = json.loads(json_str)
    
    # Extract the result data
    result_data = data['response']['result']
    
    # Create a DataFrame from the result data
    df = pd.DataFrame(result_data)
    
    # Print the DataFrame
    print(df)