diff --git a/validity/tests/test_utils/test_json.py b/validity/tests/test_utils/test_json.py index 4bc1306..9fa7766 100644 --- a/validity/tests/test_utils/test_json.py +++ b/validity/tests/test_utils/test_json.py @@ -1,4 +1,6 @@ -from validity.utils.json import transform_json +import pytest + +from validity.utils.json import jq, transform_json class TestTransformJson: @@ -31,3 +33,16 @@ def test_change_key(self): ) assert result["groups"]["admin2"] == self.JSON["groups"]["admin"] assert "admin" not in result["groups"] + + +@pytest.mark.parametrize( + "data, expression, result", + [ + ({"a": {"b": "one", "c": "two"}}, ". | mkarr(.a.b)", {"a": {"b": ["one"], "c": "two"}}), + ({"a": {"b": ["one"], "c": "two"}}, ". | mkarr(.a.b)", {"a": {"b": ["one"], "c": "two"}}), + ({"a": "10.2", "b": {"c": "20"}}, ". | mknum(.b)", {"a": "10.2", "b": {"c": 20}}), + ({"a": "10.2", "b": {"c": "20"}}, ". | mknum", {"a": 10.2, "b": {"c": 20}}), + ], +) +def test_jq(data, expression, result): + assert jq.first(expression, data) == result diff --git a/validity/utils/json.py b/validity/utils/json.py index 90100bb..81489b8 100644 --- a/validity/utils/json.py +++ b/validity/utils/json.py @@ -52,8 +52,8 @@ class jq: # ensures that expression at "pth" is an array 'def mkarr(pth): . | pth as $tgt | . | pth = if $tgt | type != "array" then [$tgt] else $tgt end', # recursively converts all number-like strings to numbers - 'def mknum(pth):. | pth as $tgt | . | pth = ' - '($tgt | walk(if type == "string" and test("[+-]?([0-9]*[.])?[0-9]+") then . | tonumber else . end))', + "def mknum(pth):. | pth as $tgt | . | pth = " + '($tgt | walk(if type == "string" and test("[+-]?([0-9]*[.])?[0-9]+") then . | tonumber else . end))', 'def mknum: walk(if type == "string" and test("[+-]?([0-9]*[.])?[0-9]+") then . | tonumber else . end)', ]