Working with nested JSON

Question:

How can I select fields from a stream of records that are contained in deeply nested JSON?

Edit this page

Example use case:

Suppose you have a topic with JSON-formatted records, but it contains nested objects. You want to write a query that can access fields in those nested objects

Code example:





Short Answer

Create a stream and use the STRUCT keyword to define the fields containing nested data

CREATE STREAM TRANSACTION_STREAM (
	      id VARCHAR,
              transaction STRUCT<num_shares INT,
             	                  amount DOUBLE,
             	                  txn_ts VARCHAR,
             	                  customer STRUCT<first_name VARCHAR,
             	                                  last_name VARCHAR,
             	                                  id INT,
             	                                  email VARCHAR>,
                                   company STRUCT<name VARCHAR,
                                                  ticker VARCHAR,
                                                  id VARCHAR,
                                                  address VARCHAR>>)
 WITH (KAFKA_TOPIC='financial_txns',
       VALUE_FORMAT='JSON',
       PARTITIONS=1);

Try it

1
Initialize the project

To get started, make a new directory anywhere you’d like for this project:

mkdir ksql-nested-json && cd ksql-nested-json

Then make the following directories to set up its structure:

mkdir src test

2
Get Confluent Platform

Next, create the following docker-compose.yml file to obtain Confluent Platform:

---
version: '2'

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:6.0.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  broker:
    image: confluentinc/cp-kafka:6.0.0
    hostname: broker
    container_name: broker
    depends_on:
      - zookeeper
    ports:
      - "29092:29092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://broker:9092,PLAINTEXT_HOST://localhost:29092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0

  schema-registry:
    image: confluentinc/cp-schema-registry:6.0.0
    hostname: schema-registry
    container_name: schema-registry
    depends_on:
      - broker
    ports:
      - "8081:8081"
    environment:
      SCHEMA_REGISTRY_HOST_NAME: schema-registry
      SCHEMA_REGISTRY_KAFKASTORE_BOOTSTRAP_SERVERS: 'broker:9092'

  ksqldb-server:
    image: confluentinc/ksqldb-server:0.11.0
    hostname: ksqldb-server
    container_name: ksqldb-server
    depends_on:
      - broker
      - schema-registry
    ports:
      - "8088:8088"
    environment:
      KSQL_CONFIG_DIR: "/etc/ksqldb"
      KSQL_LOG4J_OPTS: "-Dlog4j.configuration=file:/etc/ksqldb/log4j.properties"
      KSQL_BOOTSTRAP_SERVERS: "broker:9092"
      KSQL_HOST_NAME: ksqldb-server
      KSQL_LISTENERS: "http://0.0.0.0:8088"
      KSQL_CACHE_MAX_BYTES_BUFFERING: 0
      KSQL_KSQL_SCHEMA_REGISTRY_URL: "http://schema-registry:8081"
      KSQL_KSQL_STREAMS_AUTO_OFFSET_RESET: "earliest"

  ksqldb-cli:
    image: confluentinc/ksqldb-cli:0.11.0
    container_name: ksqldb-cli
    depends_on:
      - broker
      - ksqldb-server
    entrypoint: /bin/sh
    tty: true
    environment:
      KSQL_CONFIG_DIR: "/etc/ksqldb"
    volumes:
      - ./src:/opt/app/src
      - ./test:/opt/app/test

And launch it by running:

docker-compose up -d

3
Problem description

Let’s say you have a topic financial_txns, containing stock purchase at your firm. You want to do some basic reporting that includes the the number of shares, customer-id, and the ticker symbol involved in the transaction. All the information is in the record, but it’s in JSON format and the information you need is nested. Here’s an example record:

{
  "id": "STBCKS289803838HHDHD",
  "transaction": {
       "num_shares": 50000,     (1)
       "amount": 50044568.89,
       "txn_ts": "2020-11-18 02:31:43",
       "customer": {
             "first_name": "Jill",
             "last_name": "Smith",
             "id": 1234567,          (2)
             "email": "jsmith@gmail.com"

       },
       "company": {
             "name": "ACME Corp",
             "ticker": "ACMC",       (3)
             "id": "ACME837275222752952",
             "address": "Anytown USA, 333333"

       }
  }

}
1 Number of shares
2 Customer Id
3 The ticker symbol

As you can see, all the information is there, but you need to way to navigate this nested JSON to extract only the bits of information you are interested in.

4
Create the ksqlDB stream interactively using the CLI

To begin developing interactively, open up the ksqlDB CLI:

docker exec -it ksqldb-cli ksql http://ksqldb-server:8088

The first thing we do is to create a stream TRANSACTION_STREAM based off stock purchase transactions topic financial_txns. Within the CREATE STREAM statement, you’ll use a STRUCT keyword to define each nested object.

To quote the ksqlDB documentation "A struct represents strongly typed structured, or nested, data. A struct is an ordered collection of named fields that have a specific type."

Please note that the example in this tutorial, the nested JSON structures have the same number fields for every transaction. If you have a situation where the nested objects contain a variable number of fields then you’ll need to use the ksqlDB MAP function as described in this blog post.

CREATE STREAM TRANSACTION_STREAM (
	      id VARCHAR,
              transaction STRUCT<num_shares INT,     (1)
             	                  amount DOUBLE,
             	                  txn_ts VARCHAR,
             	                  customer STRUCT<first_name VARCHAR,  (2)
             	                                  last_name VARCHAR,
             	                                  id INT,
             	                                  email VARCHAR>,
                                   company STRUCT<name VARCHAR,        (3)
                                                  ticker VARCHAR,
                                                  id VARCHAR,
                                                  address VARCHAR>>)
 WITH (KAFKA_TOPIC='financial_txns',
       VALUE_FORMAT='JSON',
       PARTITIONS=1);
1 The entire stock transaction is nested so we create a STRUCT
2 The nested customer fields
3 The nested company fields

Go ahead and create the stream now by pasting this statement into the ksqlDB window you opened at the beginning of this step. After you’ve created the stream, quit the ksqlDB CLI for now by typing exit.

5
Produce events to the input topic

Now let’s produce some records for the TRANSACTION_STREAM stream

docker exec -i broker /usr/bin/kafka-console-producer --broker-list broker:9092 --topic financial_txns

After starting the console producer it will wait for your input. To send all send all the stock transactions click on the clipboard icon on the right, then paste the following into the terminal and press enter:

{ "id": "1", "transaction": { "num_shares": 50000, "amount": 50044568.89, "txn_ts": "2020-11-18 02:31:43", "customer": { "first_name": "Jill", "last_name": "Smith", "id": 1234567, "email": "jsmith@gmail.com" }, "company": { "name": "ACME Corp", "ticker": "ACMC", "id": "ACME837275222752952", "address": "Anytown USA, 333333" } } }
{ "id": "2", "transaction": { "num_shares": 30000, "amount": 5004.89, "txn_ts": "2020-11-18 02:35:43", "customer": { "first_name": "Art", "last_name": "Vandeley", "id": 8976612, "email": "avendleay@gmail.com" }, "company": { "name": "Imports Corp", "ticker": "IMPC", "id": "IMPC88875222752952", "address": "Anytown USA, 333333" } } }
{ "id": "3", "transaction": { "num_shares": 3000000, "amount": 600044568.89, "txn_ts": "2020-11-18 02:36:43", "customer": { "first_name": "John", "last_name": "England", "id": 456321, "email": "je@gmail.com" }, "company": { "name": "Hechinger", "ticker": "HECH", "id": "HECH8333785222752952", "address": "Anytown USA, 333333" } } }
{ "id": "4", "transaction": { "num_shares": 10000, "amount": 80044.89, "txn_ts": "2020-11-18 02:37:43", "customer": { "first_name": "Fred", "last_name": "Pym", "id": 333567, "email": "fjone@gmail.com" }, "company": { "name": "PymTech", "ticker": "PYMT", "id": "PYME837275222714197419202020", "address": "Anytown USA, 333333" } } }

After you’ve sent the records above, you can close the console producer by entering CTRL+C.

6
Run the streaming report interactively with the ksqldb-cli

To begin developing interactively, open up the ksqlDB CLI:

docker exec -it ksqldb-cli ksql http://ksqldb-server:8088

Set ksqlDB to process data from the beginning of each Kafka topic.

SET 'auto.offset.reset' = 'earliest';

Then let’s adjust the column width so we can easily see the results of the query

SET CLI COLUMN-WIDTH 10

We need to create a query that extracts the fields we want in our report. Since we modeled each field containing a nested data using a struct, we can write the query using the operator operator to retrieve the data from specific nested fields.

Notice that we can navigate to any depth with the operator, so using arbitrarily nested JSON is no problem for ksqlDB.

SELECT
    TRANSACTION->num_shares AS SHARES,
    TRANSACTION->CUSTOMER->ID as CUST_ID,
    TRANSACTION->COMPANY->TICKER as SYMBOL
FROM
    TRANSACTION_STREAM
EMIT CHANGES
LIMIT 4;

This query should produce the following output:

+----------+----------+----------+
|SHARES    |CUST_ID   |SYMBOL    |
+----------+----------+----------+
|50000     |1234567   |ACMC      |
|30000     |8976612   |IMPC      |
|3000000   |456321    |HECH      |
|10000     |333567    |PYMT      |
Limit Reached
Query terminated

Now that the reporting query works, let’s update it to create a continous query for your reporting scenario

CREATE STREAM FINANCIAL_REPORTS AS
    SELECT
    TRANSACTION->num_shares AS SHARES,
    TRANSACTION->CUSTOMER->ID as CUST_ID,
    TRANSACTION->COMPANY->TICKER as SYMBOL
FROM
    TRANSACTION_STREAM;

We’re done with the ksqlDB CLI for now so go ahead and type exit to quit.

7
Write your statements to a file

Now that you have a series of statements that’s doing the right thing, the last step is to put them into a file so that they can be used outside the CLI session. Create a file at src/statements.sql with the following content:

CREATE STREAM TRANSACTION_STREAM (
        id VARCHAR,
              transaction STRUCT<num_shares INT,
                                amount DOUBLE,
                                txn_ts VARCHAR,
                                customer STRUCT<first_name VARCHAR,
                                                last_name VARCHAR,
                                                id INT,
                                                email VARCHAR>,
                                   company STRUCT<name VARCHAR,
                                                  ticker VARCHAR,
                                                  id VARCHAR,
                                                  address VARCHAR>>)
 WITH (KAFKA_TOPIC='financial_txns',
       VALUE_FORMAT='JSON',
       PARTITIONS=1);


CREATE STREAM FINANCIAL_REPORTS AS
    SELECT
    TRANSACTION->num_shares AS SHARES,
    TRANSACTION->CUSTOMER->ID as CUST_ID,
    TRANSACTION->COMPANY->TICKER as SYMBOL
FROM
    TRANSACTION_STREAM;

Test it

1
Create the test data

Create a file at test/input.json with the inputs for testing:

{
  "inputs": [
    {
      "topic": "financial_txns",
      "value": {
       "id": "1",
       "transaction": {
        "num_shares": 50000,
        "amount": 50044568.89,
        "txn_ts": "2020-11-18 02:31:43",
        "customer": {
            "first_name": "Jill",
            "last_name": "Smith",
            "id": 1234567,
            "email": "jsmith@gmail.com"
        },
        "company": {
             "name": "ACME Corp",
             "ticker": "ACMC",
             "id": "ACME837275222752952",
             "address":
             "Anytown USA, 333333"
         }
        }
      }
    },
    {
      "topic": "financial_txns",
      "value": {
          "id": "2",
          "transaction": {
            "num_shares": 30000,
            "amount": 5004.89,
            "txn_ts": "2020-11-18 02:35:43",
            "customer": {
               "first_name": "Art",
               "last_name": "Vandeley",
               "id": 8976612,
               "email": "avendleay@gmail.com"
             },
             "company": {
               "name": "Imports Corp",
               "ticker": "IMPC",
               "id": "IMPC88875222752952",
               "address": "Anytown USA, 333333"
             }
          }
      }
    },
    {
      "topic": "financial_txns",
      "value": {
        "id": "3",
        "transaction": {
          "num_shares": 3000000,
          "amount": 600044568.89,
          "txn_ts": "2020-11-18 02:36:43",
          "customer": {
            "first_name": "John",
            "last_name": "England",
            "id": 456321,
            "email": "je@gmail.com"
          },
          "company": {
            "name": "Hechinger",
            "ticker": "HECH",
            "id": "HECH8333785222752952",
            "address":
            "Anytown USA, 333333"
          }
        }
      }
    },
    {
      "topic": "financial_txns",
      "value": {
       "id": "4",
       "transaction": {
          "num_shares": 10000,
          "amount": 80044.89,
          "txn_ts": "2020-11-18 02:37:43",
          "customer": {
            "first_name": "Fred",
            "last_name": "Pym",
            "id": 333567,
            "email": "fjone@gmail.com"
          },
          "company": {
            "name": "PymTech",
            "ticker": "PYMT",
            "id": "PYME837275222714197419202020",
            "address": "Anytown USA, 333333"
          }
        }
      }
    }
  ]
}

Create a file at test/output.json with the expected outputs:

{
  "outputs": [
    {
      "topic": "FINANCIAL_REPORTS",
      "value": {
        "SHARES" : 50000,
        "CUST_ID": 1234567,
        "SYMBOL" : "ACMC"
      }
    },
    {
      "topic": "FINANCIAL_REPORTS",
      "value": {
         "SHARES" : 30000 ,
         "CUST_ID": 8976612,
         "SYMBOL" : "IMPC"
      }
    },
    {
      "topic": "FINANCIAL_REPORTS",
      "value": {
         "SHARES" : 3000000 ,
         "CUST_ID": 456321,
         "SYMBOL" : "HECH"
      }
    },
    {
      "topic": "FINANCIAL_REPORTS",
      "value": {
         "SHARES" : 10000 ,
        "CUST_ID": 333567,
        "SYMBOL" : "PYMT"
      }
    }
  ]
}

2
Invoke the tests

Invoke the tests using the ksqlDB test runner and the statements file that you created earlier:

docker exec ksqldb-cli ksql-test-runner -i /opt/app/test/input.json -s /opt/app/src/statements.sql -o /opt/app/test/output.json

Which should pass:

	 >>> Test passed!

Take it to production

1
Send the statements to the REST API

Create a file at src/statements.sql with the following content that represents the statements we tested above without the test data.

CREATE STREAM TRANSACTION_STREAM (
        id VARCHAR,
              transaction STRUCT<num_shares INT,
                                amount DOUBLE,
                                txn_ts VARCHAR,
                                customer STRUCT<first_name VARCHAR,
                                                last_name VARCHAR,
                                                id INT,
                                                email VARCHAR>,
                                   company STRUCT<name VARCHAR,
                                                  ticker VARCHAR,
                                                  id VARCHAR,
                                                  address VARCHAR>>)
 WITH (KAFKA_TOPIC='financial_txns',
       VALUE_FORMAT='JSON',
       PARTITIONS=1);


CREATE STREAM FINANCIAL_REPORTS AS
    SELECT
    TRANSACTION->num_shares AS SHARES,
    TRANSACTION->CUSTOMER->ID as CUST_ID,
    TRANSACTION->COMPANY->TICKER as SYMBOL
FROM
    TRANSACTION_STREAM;

Launch your statements into production by sending them to the REST API with the following command:

tr '\n' ' ' < src/statements.sql | \
sed 's/;/;\'$'\n''/g' | \
while read stmt; do
    echo '{"ksql":"'$stmt'", "streamsProperties": {}}' | \
        curl -s -X "POST" "http://localhost:8088/ksql" \
             -H "Content-Type: application/vnd.ksql.v1+json; charset=utf-8" \
             -d @- | \
        jq
done

Deploy on Confluent Cloud

1
Run your app to Confluent Cloud

Instead of running a local Kafka cluster, you may use Confluent Cloud, a fully-managed Apache Kafka service.

First, create your Kafka cluster in Confluent Cloud. Use the promo code CC100KTS to receive an additional $100 free usage (details).

Next, from the Confluent Cloud UI, click on Tools & client config to get the cluster-specific configurations, e.g. Kafka cluster bootstrap servers and credentials, Confluent Cloud Schema Registry and credentials, etc., and set the appropriate parameters in your client application.

Now you’re all set to run your streaming application locally, backed by a Kafka cluster fully managed by Confluent Cloud.