Skip to content

Commit

Permalink
feat: add json macro
Browse files Browse the repository at this point in the history
  • Loading branch information
cverhoef committed Sep 4, 2024
1 parent cc9398b commit 2e8595f
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ This dbt package contains macros for SQL functions to run the dbt project on mul
- [String functions](#String-functions)
- [charindex](#charindex-source)
- [concat](#concat-source)
- [json](#json-source)
- [Aggregate functions](#Aggregate-functions)
- [stddev](#stddev-source)
- [string_agg](#string_agg-source)
Expand Down Expand Up @@ -275,6 +276,12 @@ Usage:
To pass a string as argument, make sure to use double quotes:
`{{ pm_utils.concat('"Field_A"', "' - '", '"Field_B"') }}`

#### json ([source](macros/string_functions/json.sql))
This macro returns the value defined in the path of a JSON string. The first argument indicates the field that stores the JSON string and the second argument is the path for which the value should be returned.

Usage:
`{{ pm_utils.json('[field]', '[path]') }}`

### Aggregate functions

#### stddev ([source](macros/aggregate_functions/stddev.sql))
Expand Down
9 changes: 9 additions & 0 deletions integration_tests/models/schema.yml
Original file line number Diff line number Diff line change
Expand Up @@ -171,3 +171,12 @@ models:
- equal_value:
actual: '"Only_weekend"'
expected: '"Only_weekend_expected"'

- name: test_json
tests:
- equal_value:
actual: '"One_level_field"'
expected: '"One_level_field_expected"'
- equal_value:
actual: '"Two_level_field"'
expected: '"Two_level_field_expected"'
16 changes: 16 additions & 0 deletions integration_tests/models/test_json.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
with Input_data as (
select
'{"Field_A":"ABC"}' as "Column_A",
'{"Field_A": {"Field_B": "DEF"}}' as "Column_B",
null as "Column_C"
)

select
{# Get value from a one level path. #}
{{ pm_utils.json('"Column_A"', 'Field_A') }} as "One_level_field",
'ABC' as "One_level_field_expected",

{# Get value from a two level path. #}
{{ pm_utils.json('"Column_B"', 'Field_A.Field_B') }} as "Two_level_field",
'DEF' as "Two_level_field_expected"
from Input_data
9 changes: 9 additions & 0 deletions macros/string_functions/json.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{% macro json(field, path) %}

{% if target.type == 'snowflake' %}
JSON_EXTRACT_PATH_TEXT({{ field }}, '{{ path }}')
{% elif target.type == 'sqlserver' %}
json_value({{ field }}, '{{ path }}')
{% endif %}

{% endmacro %}

0 comments on commit 2e8595f

Please sign in to comment.