简体   繁体   English

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

[英]Read Json files from Azure blob using python?

I need to read a JSON file from a blob container in Azure for doing some transformation on top of the JSON Files.我需要从 Azure 中的 blob 容器中读取 JSON 文件,以便在 JSON 文件之上进行一些转换。 I have seen few documentation and StackOverflow answers and developed a python code that will read the files from the blob.我看过很少的文档和 StackOverflow 答案,并开发了一个 python 代码,该代码将从 blob 中读取文件。

I have tried the below script from one of the Stackoverflow answers to read JSON file but I get the below error我已经从 Stackoverflow 答案之一尝试了以下脚本来读取 JSON 文件,但出现以下错误

"TypeError: the JSON object must be str, bytes or byte array, not BytesIO" “TypeError:JSON object 必须是 str、字节或字节数组,而不是 BytesIO”

I am new to python programming so not sure of the issue in the code.我是 python 编程的新手,所以不确定代码中的问题。 I tried with download_stream.content_as_text() but the file doesnt read the file without any error.我尝试使用 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)

You can use readall function.您可以使用readall function。 Please try this code:请尝试以下代码:

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)

Result:结果: 在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM