Search in sources :

Example 1 with JsonPathTokenizer

use of io.confluent.ksql.util.json.JsonPathTokenizer in project ksql by confluentinc.

the class JsonExtractStringKudf method ensureInitialized.

private void ensureInitialized(final Object[] args) {
    if (tokens != null) {
        return;
    }
    final String path = args[1].toString();
    final JsonPathTokenizer tokenizer = new JsonPathTokenizer(path);
    tokens = ImmutableList.copyOf(tokenizer);
}
Also used : JsonPathTokenizer(io.confluent.ksql.util.json.JsonPathTokenizer)

Example 2 with JsonPathTokenizer

use of io.confluent.ksql.util.json.JsonPathTokenizer in project ksql by confluentinc.

the class JsonExtractString method extract.

@Udf
public String extract(@UdfParameter(description = "The input JSON string") final String input, @UdfParameter(description = "The JSONPath to extract") final String path) {
    if (input == null || path == null) {
        return null;
    }
    if (latestPath == null || !latestPath.equals(path)) {
        final JsonPathTokenizer tokenizer = new JsonPathTokenizer(path);
        latestTokens = ImmutableList.copyOf(tokenizer);
        latestPath = path;
    }
    JsonNode currentNode = UdfJsonMapper.parseJson(input);
    for (final String token : latestTokens) {
        if (currentNode instanceof ArrayNode) {
            try {
                final int index = Integer.parseInt(token);
                currentNode = currentNode.get(index);
            } catch (final NumberFormatException e) {
                return null;
            }
        } else {
            currentNode = currentNode.get(token);
        }
        if (currentNode == null) {
            return null;
        }
    }
    if (currentNode.isTextual()) {
        return currentNode.asText();
    } else {
        return currentNode.toString();
    }
}
Also used : JsonPathTokenizer(io.confluent.ksql.util.json.JsonPathTokenizer) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Udf(io.confluent.ksql.function.udf.Udf)

Aggregations

JsonPathTokenizer (io.confluent.ksql.util.json.JsonPathTokenizer)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ArrayNode (com.fasterxml.jackson.databind.node.ArrayNode)1 Udf (io.confluent.ksql.function.udf.Udf)1