2

I'm trying to read a JSON key file from Google Cloud Storage to authenticate. I have the following function:

storage_client = storage.Client()
bucket_name = 'bucket_name'
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.get_blob('key.json')
json_data_string = blob.download_as_string()

credentials = ServiceAccountCredentials.from_json_keyfile_dict(
    json_data_string,
    scopes=['https://www.googleapis.com/auth/analytics',
            'https://www.googleapis.com/auth/analytics.edit'])

and the following error: AttributeError: 'bytes' object has no attribute 'get'

How should I read/format my key.json file to use it with ServiceAccountCredentials

1 Answer 1

2

The download_as_string() function returns bytes, but from_json_keyfile_dict() expects a dict. You need to first decode the bytes to turn it into a string:

json_data_string = blob.download_as_string().decode('utf8')

And then load this string as a dict:

import json
json_data_dict = json.loads(json_data_string)

And then you can call:

credentials = ServiceAccountCredentials.from_json_keyfile_dict(
    json_data_dict,
    scopes=['https://www.googleapis.com/auth/analytics',
            'https://www.googleapis.com/auth/analytics.edit'])
Sign up to request clarification or add additional context in comments.

3 Comments

What are bytes exactly? Is there a way to directly access json file from storage in the proper format?
See stackoverflow.com/questions/10060411/…. The "proper format" is subjective here, Cloud Storage just stores binary blobs, so it's up to you to turn it into the format you're expecting it to be.
Ok. so whatever I extract from Cloud Storage it will always be binary blobs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.