I have a string (str_json) that I’m getting from elsewhere :
JavaScript
x
26
26
1
{
2
'ARN': 'arn:aws:secretsmanager:xxx:xxx:secret:xx/xxx-xxx',
3
'Name': 'xxx/local',
4
'VersionId': 'xxx-xxx-xxx-xxx-xxx',
5
'SecretString': 'E:\path\to\folder\project\xxx.json',
6
'VersionStages': ['AWSCURRENT'],
7
'CreatedDate': datetime.datetime(2022, 9, 28, 8, 25, 35, 329448, tzinfo = tzlocal()),
8
'ResponseMetadata': {
9
'RequestId': 'xxx',
10
'HTTPStatusCode': 200,
11
'HTTPHeaders': {
12
'content-type': 'application/x-amz-json-1.1',
13
'content-length': '306',
14
'x-amzn-requestid': 'xxx',
15
'connection': 'close',
16
'access-control-allow-origin': '*',
17
'access-control-allow-methods': 'HEAD,GET,PUT,POST,DELETE,OPTIONS,PATCH',
18
'access-control-allow-headers': 'authorization,cache-control,content-length,content-md5,content-type,etag,location,x-amz-acl,x-amz-content-sha256,x-amz-date,x-amz-request-id,x-amz-security-token,x-amz-tagging,x-amz-target,x-amz-user-agent,x-amz-version-id,x-amzn-requestid,x-localstack-target,amz-sdk-invocation-id,amz-sdk-request',
19
'access-control-expose-headers': 'etag,x-amz-version-id',
20
'date': 'Wed, 28 Sep 2022 02:56:14 GMT',
21
'server': 'xxx'
22
},
23
'RetryAttempts': 0
24
}
25
}
26
This is a string str_json
which is supposed to be JSON but it actually contains some python code and a number value and single quotes.
json.loads
will fail.
What I need is the JSON string of str_json.
json_data = json.loads(str_json)
What I’ve attempted so far :
JavaScript
1
6
1
e = eval(str_json)
2
e['ResponseMetadata']['RetryAttempts'] = "0"
3
str_json = '"'.join(str(e).split("'"))
4
json_data = json.loads(str(str_json))
5
print(json_data)
6
Advertisement
Answer
You can handle that datetime thingy like this, which converts the datetime into proper json:
JavaScript
1
10
10
1
def datahandler(obj):
2
if isinstance(obj, datetime.datetime):
3
return obj.isoformat()
4
raise TypeError("Unknown type")
5
6
def main(argv):
7
client = boto3.client("ec2")
8
regions = client.describe_regions() # type(regions) == dict
9
jregions = json.dumps(regions, sort_keys=True, default=datahandler) # type(jregions) == str
10