@@ -44,6 +44,7 @@ def default(self, obj: Any) -> Any:
4444
4545class JSONFormat (Format ):
4646 CONTENT_TYPE : Final [str ] = "application/cloudevents+json"
47+ DEFAULT_CONTENT_TYPE : Final [str ] = "application/json"
4748 JSON_CONTENT_TYPE_PATTERN : Pattern [str ] = re .compile (
4849 r"^(application|text)/([a-zA-Z0-9\-\.]+\+)?json(;.*)?$"
4950 )
@@ -135,7 +136,9 @@ def write(self, event: BaseCloudEvent) -> bytes:
135136 "utf-8"
136137 )
137138 else :
138- datacontenttype = event_dict .get ("datacontenttype" , "application/json" )
139+ datacontenttype = event_dict .get (
140+ "datacontenttype" , self .DEFAULT_CONTENT_TYPE
141+ )
139142 if re .match (JSONFormat .JSON_CONTENT_TYPE_PATTERN , datacontenttype ):
140143 event_dict ["data" ] = event_data
141144 else :
@@ -171,12 +174,19 @@ def write_data(
171174
172175 # If data is a dict and content type is JSON, serialize as JSON
173176 if isinstance (data , dict ):
174- if datacontenttype and re .match (
175- JSONFormat .JSON_CONTENT_TYPE_PATTERN , datacontenttype
176- ):
177+ content_type = datacontenttype or self .DEFAULT_CONTENT_TYPE
178+ if re .match (JSONFormat .JSON_CONTENT_TYPE_PATTERN , content_type ):
177179 return dumps (data , cls = _JSONEncoderWithDatetime ).encode ("utf-8" )
178180
179- # Default: convert to string and encode
181+ # for other contenttypes we still try to generate a json-decodable string
182+ # if not possible, a string representing
183+ try :
184+ return dumps (data , cls = _JSONEncoderWithDatetime ).encode ("utf-8" )
185+ except TypeError :
186+ pass
187+
188+ # according to the spec, we return an encoded string per default
189+ # careful: the result is not json-decodable as the dict keys are single-quoted
180190 return str (data ).encode ("utf-8" )
181191
182192 def read_data (
@@ -196,9 +206,8 @@ def read_data(
196206 return None
197207
198208 # If content type indicates JSON, try to parse as JSON
199- if datacontenttype and re .match (
200- JSONFormat .JSON_CONTENT_TYPE_PATTERN , datacontenttype
201- ):
209+ content_type = datacontenttype or self .DEFAULT_CONTENT_TYPE
210+ if re .match (JSONFormat .JSON_CONTENT_TYPE_PATTERN , content_type ):
202211 try :
203212 decoded = body .decode ("utf-8" )
204213 parsed : dict [str , Any ] = loads (decoded )
0 commit comments