Search code examples
pythongoogle-cloud-platformgoogle-cloud-functionsgoogle-cloud-storage

modify existing json in cloud storage using cloud functions - python


I need to modify the key values in the existing json file in google cloud storage using cloud functions.

My existing json file in the bucket looks like this:

{"stuID": "", "stuName": "", "marks": ""}

Getting this error with my code:

TypeError: write() argument must be str, not dict

I tried below:

def hello_gcs(event, context):
    file = event
    my_file = event['name']
    bucket_name = event['bucket']

    json_data = modify_json(bucket_name, my_file)

def modify_json(bucket_name, my_file):
    # Extract data and load as json
    file_name = my_file
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(file_name)
    content = blob.download_as_text()
    json_data = json.loads(content)

    # modify the json data
    json_data['stuID'] = 's001'

    # update back in gcs
    with blob.open("w") as f:
     f.write(str(json_data))
     f.close()

    return json_data

Solution

  • Publishing this as a community wiki for others sake.

    As mentioned by @Avión

    Use f.write(json.dumps(json_data)) instead of f.write(str(json_data)).