From 65eef00cc70dabe5da70cff71aa2b7acf1306eae Mon Sep 17 00:00:00 2001 From: Vinit Kumar Date: Wed, 20 Apr 2022 02:10:35 +0530 Subject: [PATCH] fix: issue with wrong output for boolean list --- examples/booleanjson2.json | 5 +++++ json2xml/dicttoxml.py | 9 ++++++--- tests/test_json2xml.py | 9 +++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) create mode 100644 examples/booleanjson2.json diff --git a/examples/booleanjson2.json b/examples/booleanjson2.json new file mode 100644 index 0000000..95a35a8 --- /dev/null +++ b/examples/booleanjson2.json @@ -0,0 +1,5 @@ +{ + "boolean_list": [true, false], + "number_array": [1, 2, 3], + "string_array": ["a", "b", "c"] +} \ No newline at end of file diff --git a/json2xml/dicttoxml.py b/json2xml/dicttoxml.py index 489d55f..6c3b0e7 100755 --- a/json2xml/dicttoxml.py +++ b/json2xml/dicttoxml.py @@ -137,6 +137,7 @@ def convert(obj, ids, attr_type, item_func, cdata, item_wrap, parent="root"): LOG.info(f'Inside convert(). obj type is: "{type(obj).__name__}", obj="{str(obj)}"') + item_name = item_func(parent) # since bool is also a subtype of number.Number and int, the check for bool @@ -265,7 +266,11 @@ def convert_list(items, ids, parent, attr_type, item_func, cdata, item_wrap): f'Looping inside convert_list(): item="{str(item)}", item_name="{item_name}", type="{type(item).__name__}"' ) attr = {} if not ids else {"id": f"{this_id}_{i + 1}"} - if isinstance(item, (numbers.Number, str)): + + if isinstance(item, bool): + addline(convert_bool(item_name, item, attr_type, attr, cdata)) + + elif isinstance(item, (numbers.Number, str)): if item_wrap: addline( convert_kv( @@ -298,8 +303,6 @@ def convert_list(items, ids, parent, attr_type, item_func, cdata, item_wrap): ) ) - elif isinstance(item, bool): - addline(convert_bool(item_name, item, attr_type, attr, cdata)) elif isinstance(item, dict): item_dict_str = convert_dict( diff --git a/tests/test_json2xml.py b/tests/test_json2xml.py index 872ee32..54ef4d5 100644 --- a/tests/test_json2xml.py +++ b/tests/test_json2xml.py @@ -184,3 +184,12 @@ def test_read_boolean_data_from_json(self): dict_from_xml = xmltodict.parse(result) assert dict_from_xml["all"]["boolean"]["#text"] != 'True' assert dict_from_xml["all"]["boolean"]["#text"] == 'true' + + + def test_read_boolean_data_from_json2(self): + """Test correct return for boolean types.""" + data = readfromjson("examples/booleanjson2.json") + result = json2xml.Json2xml(data).to_xml() + dict_from_xml = xmltodict.parse(result) + assert dict_from_xml["all"]["item"][0]["#text"] != 'True' + assert dict_from_xml["all"]["item"][0]["#text"] == 'true'