我从 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。
有什么优雅的方法吗?
我给了你执行此操作的完整代码。
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)
使用
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())
然后,您可以将此字典加载到数据框中