在Python中解析字节数据

问题描述 投票:0回答:2

我从 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}}'

我需要提取内部结果数据(日期、id、价格),最好提取到 pandas DataFrame。

有什么优雅的方法吗?

python type-conversion
2个回答
0
投票
  1. 决定字节串:将字节串转换为常规字符串。
  2. Partse the Json Data:使用Python的json库从字符串中解析出JSOn数据。
  3. 提取数据并创建DataFrame:从解析的JSOn中提取数据并使用pandas创建DataFrame。

我给了你执行此操作的完整代码。

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)

0
投票

使用

decode()
从字节中获取字符串,使用
json.loads()
从字符串中获取字典:

import json

raw = 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}}'

## data is a dict with info
data = json.loads(raw.decode())

然后,您可以将此字典加载到数据框中

© www.soinside.com 2019 - 2024. All rights reserved.