Skip to content

Commit

Permalink
Fix datetime is not JSON serializable error (#591)
Browse files Browse the repository at this point in the history
`TypeError: datetime.date(2012, 10, 17) is not JSON serializable`

This fixes the above exception raised by json.dumps when the yaml
library loads an unquoted date value e.g. `2012-10-17` as a
`datetime.time` object.
  • Loading branch information
aarongorka authored and phobologic committed May 14, 2018
1 parent 4c58c0b commit d3f3709
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
5 changes: 3 additions & 2 deletions stacker/actions/diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def normalize_json(template):
list: json representation of the parameters
"""
obj = parse_cloudformation_template(template)
json_str = json.dumps(obj, sort_keys=True, indent=4)
json_str = json.dumps(obj, sort_keys=True, indent=4, default=str)
result = []
lines = json_str.split("\n")
for line in lines:
Expand Down Expand Up @@ -250,7 +250,8 @@ def _diff_stack(self, stack, **kwargs):
old_stack = normalize_json(
json.dumps(old_template,
sort_keys=True,
indent=4)
indent=4,
default=str)
)
print_stack_changes(stack.name, new_stack, old_stack, new_params,
old_params)
Expand Down
19 changes: 19 additions & 0 deletions stacker/tests/actions/test_diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,22 @@ def test_normalize_json(self):
'}\n'
]
self.assertEquals(normalized_template, normalize_json(template))

def test_normalize_json_date(self):
"""Ensure normalize_json handles objects loaded as datetime objects"""

template = """
AWSTemplateFormatVersion: '2010-09-09'
Description: ECS Cluster Application
Resources:
ECSTaskRoleDefault:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17 # datetime.date(2012, 10, 17)
Statement:
- Effect: Allow
Principal:
Service: ecs-tasks.amazonaws.com
Action: sts:AssumeRole"""
self.assertTrue(normalize_json(template))

0 comments on commit d3f3709

Please sign in to comment.