@@ -238,3 +238,55 @@ def test_validate_json_by_invalid_schema_file(self, json):
238238 schema_path = os .path .join (self .dir_path , "json" , "broken_schema.json" )
239239 with pytest .raises (AssertionError ):
240240 self .json_library .validate_json_by_schema_file (json , schema_path )
241+
242+ def test_add_object_to_json_issue_58 (self ):
243+ """Test for issue #58: add_object_to_json wraps entire object when path doesn't exist
244+
245+ When adding an object to a non-existent path where the path name matches a key
246+ in the object, the current implementation adds the entire object as a nested value.
247+
248+ For example, when adding {key1: value1} to $.key1:
249+ - Current behavior: {key1: {key1: value1}}
250+ - The reporter suggests: {key1: value1} by using object_to_add[child_name]
251+
252+ This test reproduces the issue to confirm the bug exists.
253+ """
254+ # Test case from issue #58
255+ # When the field name (key1) matches a key in the object being added
256+ json_obj = {"existing" : "data" }
257+ data_to_add = {"key1" : "value1" }
258+
259+ result = self .json_library .add_object_to_json (
260+ json_obj , "$.key1" , data_to_add
261+ )
262+
263+ # Current behavior: creates {key1: {key1: value1}}
264+ assert result .get ("key1" ) == data_to_add
265+ assert result .get ("key1" ) == {"key1" : "value1" }
266+
267+ # This demonstrates the nesting issue - key1 contains the entire object
268+ print (f"\n Issue #58 reproduced:" )
269+ print (f"Added { data_to_add } to path $.key1" )
270+ print (f"Result: { result } " )
271+ print (f"Value at key1: { result .get ('key1' )} " )
272+
273+ # Test case 2: When field name doesn't match keys in object
274+ # This works as expected - creates {myField: {key1: value1}}
275+ json_obj2 = {"existing" : "data" }
276+ result2 = self .json_library .add_object_to_json (
277+ json_obj2 , "$.myField" , data_to_add
278+ )
279+ assert result2 .get ("myField" ) == data_to_add
280+
281+ # Test case 3: Multiple keys scenario
282+ json_obj3 = {"existing" : "data" }
283+ data_to_add3 = {"key1" : "value1" , "key2" : "value2" }
284+ result3 = self .json_library .add_object_to_json (
285+ json_obj3 , "$.key1" , data_to_add3
286+ )
287+ # Current: {key1: {key1: value1, key2: value2}}
288+ assert result3 .get ("key1" ) == {"key1" : "value1" , "key2" : "value2" }
289+
290+ # The issue is: should it extract just result["key1"]["key1"]?
291+ # That would be: {key1: value1}
292+ # But that only works when child_name exists in the object!
0 commit comments