Skip to content

Commit

Permalink
Snow-802269 Add JsonNode function to read variant column as json obje…
Browse files Browse the repository at this point in the history
…ct (#149)

* add JsonNode function for variant type

* updadte version

* update variant type as object

* add JsonNode function for java and scala with test case

* fix imports

* update test case

* update docs

* update docs

* rebuild

* update asJsonNode impl for scala and java

* format
  • Loading branch information
sfc-gh-gmahadevan authored Aug 29, 2024
1 parent 9313150 commit e120e0b
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/main/java/com/snowflake/snowpark_java/types/Variant.java
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,26 @@ public String asJsonString() {
}
}

/**
* Return the variant value as a JsonNode. This function allows to read the JSON object directly
* as JsonNode from variant column rather parsing it as String
*
* <pre>{@code - to get the first value from array for key "a"
*
* Variant jv = new Variant("{\"a\": [1, 2], \"b\": \"c\"}");
* System.out.println(jv.asJsonNode().get("a").get(0));
*
* output
* 1
* }</pre>
*
* @return A valid JsonNode
* @since 1.14.0
*/
public JsonNode asJsonNode() {
return value;
}

/**
* Converts the variant as binary value.
*
Expand Down
17 changes: 17 additions & 0 deletions src/main/scala/com/snowflake/snowpark/types/Variant.scala
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,23 @@ class Variant private[snowpark] (
}
}

/**
* Return the variant value as a JsonNode. This function allows to read the JSON object directly
* as JsonNode from variant column rather parsing it as String
* Example - to get the first value from array for key "a"
* {{{
* val sv = new Variant("{\"a\": [1, 2], \"b\": 3, \"c\": \"xyz\"}")
* println(sv.asJsonNode().get("a").get(0))
* output
* 1
* }}}
*
* @since 1.14.0
*/
def asJsonNode(): JsonNode = {
value
}

/**
* Converts the variant as binary value
* @since 0.2.0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -365,4 +365,11 @@ public void equalsAndToString() {

assert v1.toString().equals("123");
}

@Test
public void javaJsonNodeVariantConverter() throws IllegalArgumentException {
Variant jv = new Variant("{\"a\": [1, 2], \"b\": \"c\"}");
assert (jv.asJsonNode().get("a").isArray());
assert (jv.asJsonNode().get("b").asText().equals("c"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -311,4 +311,11 @@ class ScalaVariantSuite extends FunSuite {

assert(v1.toString() == "123")
}

test("JsonNode") {
val sv = new Variant("{\"a\": [1, 2], \"b\": 3, \"c\": \"xyz\"}")
assert(sv.asJsonNode().get("a").isArray)
assert(sv.asJsonNode().get("b").asInt().equals(3))
assert(sv.asJsonNode().get("c").asText().equals("xyz"))
}
}

0 comments on commit e120e0b

Please sign in to comment.