'How to update json in s3 using python boto3?

Iam trying to update the json file which resides in the s3 bucket. I gone thorough different approach, but nothing seems working.

Below is the code

import boto3
import json

#Loading Json from s3
s3= boto3.resource('s3', aws_access_key_id='id',aws_secret_access_key='key')
obj=s3.Object('s3python','test.json')
body=obj.get()['Body'].read()
jsonContent=json.loads(body)
print(jsonContent)

I am getting following error

Error
  raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Udpate new value once if the json reading is successful below

updateJson={}
for k,v in jsonContent.items():
    updateJson[k]=v

updateJson['key']='newvalue'


json_dump_s3 = lambda obj, f: s3.Object(key=f).put(Body=json.dumps(obj))

key='test.json'
json_dump_s3(updateJson,key)
#Writing Json to s3

Can anyone help on this?



Solution 1:[1]

Just sharing the solution as it might help others who are facing the same error.

The error is due to missing decode(). So just need to replace below line :

body=obj.get()['Body'].read()

Updated :

body=obj.get()['Body'].read().decode()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1