@@ -115,6 +115,41 @@ def _flatten_with_flatten_func(
115115 return False , func_output
116116
117117
118+ def _flatten_compound_value_using_json (
119+ key : str ,
120+ value : Any ,
121+ exclude_keys : Set [str ],
122+ rename_keys : Dict [str , str ],
123+ flatten_functions : Dict [str , FlattenFunc ],
124+ _from_json = False ) -> FlattenedDict :
125+ if _from_json :
126+ _logger .debug (
127+ "Cannot flatten value with key %s; value: %s" , key , value
128+ )
129+ return {}
130+ try :
131+ json_string = json .dumps (value )
132+ except TypeError :
133+ _logger .debug (
134+ "Cannot flatten value with key %s; value: %s. Not JSON serializable." ,
135+ key ,
136+ value ,
137+ )
138+ return {}
139+ json_value = json .loads (json_string )
140+ return _flatten_value (
141+ key ,
142+ json_value ,
143+ exclude_keys = exclude_keys ,
144+ rename_keys = rename_keys ,
145+ flatten_functions = flatten_functions ,
146+ # Ensure that we don't recurse indefinitely if "json.loads()" somehow returns
147+ # a complex, compound object that does not get handled by the "primitive", "list",
148+ # or "dict" cases. Prevents falling back on the JSON serialization fallback path.
149+ _from_json = True ,
150+ )
151+
152+
118153def _flatten_compound_value (
119154 key : str ,
120155 value : Any ,
@@ -160,32 +195,13 @@ def _flatten_compound_value(
160195 rename_keys = rename_keys ,
161196 flatten_functions = flatten_functions ,
162197 )
163- if _from_json :
164- _logger .debug (
165- "Cannot flatten value with key %s; value: %s" , key , value
166- )
167- return {}
168- try :
169- json_string = json .dumps (value )
170- except TypeError :
171- _logger .debug (
172- "Cannot flatten value with key %s; value: %s. Not JSON serializable." ,
173- key ,
174- value ,
175- )
176- return {}
177- json_value = json .loads (json_string )
178- return _flatten_value (
198+ return _flatten_compound_value_using_json (
179199 key ,
180- json_value ,
200+ value ,
181201 exclude_keys = exclude_keys ,
182202 rename_keys = rename_keys ,
183203 flatten_functions = flatten_functions ,
184- # Ensure that we don't recurse indefinitely if "json.loads()" somehow returns
185- # a complex, compound object that does not get handled by the "primitive", "list",
186- # or "dict" cases. Prevents falling back on the JSON serialization fallback path.
187- _from_json = True ,
188- )
204+ _from_json = _from_json )
189205
190206
191207def _flatten_value (
0 commit comments