[英]How to read json file in cloud storage using cloud functions - python
The need is to read the json file data present in GCS bucket using cloud functions (python).需要使用云函数(python)读取 GCS 存储桶中存在的 json 文件数据。 I have uploaded the required json data to bucket and try running the cloud function.
我已将所需的 json 数据上传到存储桶并尝试运行云 function。
The input json file data:输入json文件数据:
{"count":15,"data":[{"P_ID":21.0,"P_NAME":"MMME","TZ":"PST","DATE_MODIFIED":"2005-10-14 00:00:00"}]}
here is the code:这是代码:
from google.cloud import storage
import base64
import json
import os
def hello_gcs(event, context):
"""
Triggered by a change to a Cloud Storage bucket.
Args:
event (dict): Event payload.
context (google.cloud.functions.Context): Metadata for the event.
"""
print("in CF")
print("event", event)
file_name = event['name']
bucket_name = event['bucket']
client = storage.Client()
bucket = client.get_bucket(bucket_name)
file_blob = storage.Blob(file_name, bucket)
download_data = file_blob.download_as_string().decode()
jsondata = {}
jsondata = download_data
print("download_data : ", download_data)
print("jsondata := ", jsondata)
print(jsondata['count'])
Please correct me.请纠正我。 I am not getting the data displayed in the code.
我没有得到代码中显示的数据。 this is just to test the cloud function once this is working I need to implement additional features.
这只是为了测试云 function 一旦它正常工作,我需要实现其他功能。
here is the working code.这是工作代码。 Converted the download file to json object and accessed the fields.
将下载文件转换为 json object 并访问字段。
from google.cloud import storage
import base64
import json
import os
def hello_gcs(event, context):
"""
Triggered by a change to a Cloud Storage bucket.
Args:
event (dict): Event payload.
context (google.cloud.functions.Context): Metadata for the event.
"""
print("in CF")
print("event", event)
file_name = event['name']
bucket_name = event['bucket']
client = storage.Client()
bucket = client.get_bucket(bucket_name)
file_blob = storage.Blob(file_name, bucket)
download_data = file_blob.download_as_string().decode()
print("download_data : ", download_data)
"""
jsondata = {}
jsondata = download_data
"""
jsondata = {}
#convert string to object
jsondata = json.loads(download_data)
print("jsondata => ", jsondata)
print(jsondata['count'])
The function that you use if triggered on an event, when an object is written to Cloud Storage for instance. function 在事件触发时使用,例如,当 object 写入 Cloud Storage 时。 But you only have the event, not the content.
但是你只有事件,没有内容。 With the event data, you have all that you need for downloading the file and to process it.
有了事件数据,您就拥有了下载文件和处理文件所需的一切。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.