使用 python 从 Azure blob 读取 Json 文件?

dfb*_*beg 8 python json azure-blob-storage

我需要从 Azure 中的 blob 容器读取 JSON 文件,以便在 JSON 文件之上进行一些转换。我看过一些文档和 StackOverflow 答案,并开发了一个 python 代码来从 blob 中读取文件。

我已尝试使用 Stackoverflow 答案之一中的以下脚本来读取 JSON 文件,但出现以下错误

“TypeError:JSON 对象必须是 str、bytes 或字节数组,而不是 BytesIO”

我是 python 编程新手,所以不确定代码中的问题。我尝试使用 download_stream.content_as_text() 但文件读取文件时没有任何错误。

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
from io import BytesIO
import requests
from pandas import json_normalize
import json

filename = "sample.json"

container_name="test"
constr = ""

blob_service_client = BlobServiceClient.from_connection_string(constr)
container_client=blob_service_client.get_container_client(container_name)
blob_client = container_client.get_blob_client(filename)
streamdownloader=blob_client.download_blob()

stream = BytesIO()
streamdownloader.download_to_stream(stream)
# with open(stream) as j:
#      contents = json.loads(j)
fileReader = json.loads(stream)

print(filereader)
Run Code Online (Sandbox Code Playgroud)

Ste*_*son 12

您可以使用readall函数。请尝试这个代码:

from azure.storage.blob import BlobServiceClient, BlobClient, ContainerClient
import json

filename = "sample.json"

container_name="test"
constr = ""

blob_service_client = BlobServiceClient.from_connection_string(constr)
container_client = blob_service_client.get_container_client(container_name)
blob_client = container_client.get_blob_client(filename)
streamdownloader = blob_client.download_blob()

fileReader = json.loads(streamdownloader.readall())
print(fileReader)
Run Code Online (Sandbox Code Playgroud)

结果: 在此输入图像描述