Finally, streaming!
Streaming has been the most requested jello feature for a long time, and I’m really excited to say it’s here in jello v2.0.0. A huge thank you to Steven Pelley, who did the original streaming work in PR #69.
Until now, jello always read all of its input before running your query. That’s perfect for a JSON document, but not so great for a multi-gigabyte log file, or for a stream that never ends. The new -S option fixes that: jello reads JSON Lines one at a time, runs your Python query as they arrive, and prints each result as soon as it’s ready.
In this post I’ll go over the basics, with lots of examples you can run in your own terminal on Linux, macOS, or Windows:
- Your first stream, and the one thing to remember about
_ - Filtering and reshaping with generator expressions
- Loops and
yield - Watching a live stream (with pizza!)
- Totals at the end of a stream
- Raw text lines with
-SR - Peeking at the shape with
-Ss
Streaming mode in a nutshell
- Input is read one JSON line at a time, from STDIN or from files with
-f._is an iterator over those values, not a list. Each value still supports dot notation.- If your query returns a list, generator, or iterator, each item is printed as one line of JSON as soon as it’s produced.
- Anything else (a dict, a number, a string) is printed once.
- Output is always compact JSON Lines, ready to pipe into jello, jq, or anything else.
Setup
First, make sure you have jello v2.0.0 or later. It needs Python 3.11 or later.
% jello -v jello: Version: 2.0.0 <snip>
If you see an older version, upgrade with pip3 install --upgrade jello, or download the latest release from the jello releases page on GitHub. It has standalone binaries for Linux, macOS, and Windows, a Windows MSI installer, and RPM and DEB packages.
Next, make a new folder and save these two files in it. orders.jsonl is the order log from a (very fictional) pizza shop, one order per line:
orders.jsonl
{"id":101,"time":"18:02","name":"Ada","pizza":"Margherita","size":"medium","toppings":["basil"],"price":12.5,"delivery":false}
{"id":102,"time":"18:04","name":"Linus","pizza":"Pepperoni","size":"large","toppings":["pepperoni","extra cheese"],"price":18.0,"delivery":true}
{"id":103,"time":"18:05","name":"Grace","pizza":"Hawaiian","size":"small","toppings":["ham","pineapple"],"price":10.0,"delivery":true}
{"id":104,"time":"18:09","name":"Guido","pizza":"Veggie","size":"large","toppings":["peppers","onions","olives","mushrooms"],"price":17.5,"delivery":false}
{"id":105,"time":"18:11","name":"Margaret","pizza":"Pepperoni","size":"medium","toppings":["pepperoni"],"price":14.0,"delivery":true}
{"id":106,"time":"18:15","name":"Dennis","pizza":"Four Cheese","size":"large","toppings":["mozzarella","gorgonzola","parmesan","fontina"],"price":19.0,"delivery":true}
{"id":107,"time":"18:16","name":"Barbara","pizza":"Margherita","size":"small","toppings":["basil"],"price":9.0,"delivery":false}
{"id":108,"time":"18:20","name":"Ken","pizza":"Meat Lovers","size":"large","toppings":["pepperoni","sausage","bacon","ham"],"price":21.0,"delivery":true}
{"id":109,"time":"18:23","name":"Hedy","pizza":"Veggie","size":"medium","toppings":["peppers","onions","anchovies"],"price":13.5,"delivery":true}
{"id":110,"time":"18:27","name":"Alan","pizza":"Pepperoni","size":"large","toppings":["pepperoni","jalapenos"],"price":18.5,"delivery":false}
And oven.py is a tiny Python script that cooks up a never-ending stream of random orders. It only uses the Python standard library:
oven.py
# oven.py - a never-ending stream of pizza orders, one JSON object per line
import json, os, random, sys, time
NAMES = ["Ada", "Linus", "Grace", "Guido", "Margaret", "Dennis", "Barbara", "Ken", "Hedy", "Alan"]
MENU = {"Margherita": 9, "Pepperoni": 11, "Hawaiian": 11, "Veggie": 10, "Four Cheese": 12, "Meat Lovers": 13}
EXTRAS = ["extra cheese", "mushrooms", "olives", "jalapenos", "anchovies", "pineapple"]
SIZES = {"small": 0, "medium": 3, "large": 6}
order_id = 1000
try:
while True:
order_id += 1
pizza = random.choice(list(MENU))
size = random.choice(list(SIZES))
toppings = random.sample(EXTRAS, random.randint(0, 2))
order = {
"id": order_id,
"time": time.strftime("%H:%M:%S"),
"name": random.choice(NAMES),
"pizza": pizza,
"size": size,
"toppings": toppings,
"price": MENU[pizza] + SIZES[size] + 1.5 * len(toppings),
"delivery": random.random() < 0.6,
}
print(json.dumps(order), flush=True)
time.sleep(random.uniform(0.3, 1.2))
except (BrokenPipeError, KeyboardInterrupt):
# jello stopped reading (or you pressed Ctrl-C): exit quietly
os.dup2(os.open(os.devnull, os.O_WRONLY), sys.stdout.fileno())
On Windows: run the examples in PowerShell 7.3 or later. (Windows PowerShell 5.1 strips the double quotes inside the queries.) Use
pythoninstead ofpython3. If your shell gives you quoting trouble, put any query in a file and run it with-q query.py, which works everywhere.
Hello, stream
Let’s start by streaming the orders straight through with no query:
% jello -S -f orders.jsonl
{"id":101,"time":"18:02","name":"Ada","pizza":"Margherita","size":"medium","toppings":["basil"],"price":12.5,"delivery":false}
{"id":102,"time":"18:04","name":"Linus","pizza":"Pepperoni","size":"large","toppings":["pepperoni","extra cheese"],"price":18.0,"delivery":true}
{"id":103,"time":"18:05","name":"Grace","pizza":"Hawaiian","size":"small","toppings":["ham","pineapple"],"price":10.0,"delivery":true}
{"id":104,"time":"18:09","name":"Guido","pizza":"Veggie","size":"large","toppings":["peppers","onions","olives","mushrooms"],"price":17.5,"delivery":false}
{"id":105,"time":"18:11","name":"Margaret","pizza":"Pepperoni","size":"medium","toppings":["pepperoni"],"price":14.0,"delivery":true}
{"id":106,"time":"18:15","name":"Dennis","pizza":"Four Cheese","size":"large","toppings":["mozzarella","gorgonzola","parmesan","fontina"],"price":19.0,"delivery":true}
{"id":107,"time":"18:16","name":"Barbara","pizza":"Margherita","size":"small","toppings":["basil"],"price":9.0,"delivery":false}
{"id":108,"time":"18:20","name":"Ken","pizza":"Meat Lovers","size":"large","toppings":["pepperoni","sausage","bacon","ham"],"price":21.0,"delivery":true}
{"id":109,"time":"18:23","name":"Hedy","pizza":"Veggie","size":"medium","toppings":["peppers","onions","anchovies"],"price":13.5,"delivery":true}
{"id":110,"time":"18:27","name":"Alan","pizza":"Pepperoni","size":"large","toppings":["pepperoni","jalapenos"],"price":18.5,"delivery":false}
Notice the output is compact JSON Lines: one order per line. That’s the deal in streaming mode. Whatever comes out comes out one line at a time, so you can pipe it into another jello, jq, or anything else that reads JSON Lines.
Note:
-fmust be the last option, so the query goes before it.
Now here’s the one thing to remember about streaming mode: _ is no longer a list. It’s an iterator that hands you one order at a time. If you try your usual dot notation on it, jello will point you in the right direction:
% jello -S _.pizza -f orders.jsonl
jello: Query Exception: AttributeError
Jello query, line 1
_.pizza
'generator' object has no attribute 'pizza'
Hint: In streaming mode (-S) "_" is an iterator over the input values,
not a list or dict. Loop over it instead, e.g. (x.foo for x in _) or
a for loop with yield.
query: _.pizza
Instead, we loop over _. Which brings us to my favorite part.
Generator expressions are your new best friend
A generator expression is a for loop wrapped in parentheses, and it’s the perfect shape for streaming: jello prints each value the moment it’s ready. Let’s grab every customer’s name:
% jello -S '(o.name for o in _)' -f orders.jsonl "Ada" "Linus" "Grace" "Guido" "Margaret" "Dennis" "Barbara" "Ken" "Hedy" "Alan"
Add an if to filter, and -r to print strings without the quotes. Who ordered a large?
% jello -Sr '(o.name for o in _ if o.size == "large")' -f orders.jsonl Linus Guido Dennis Ken Alan
Since it’s all just Python, f-strings work great. Here’s a ticket for each delivery order:
% jello -Sr '(f"#{o.id} {o.name}: {o.size} {o.pizza} ${o.price:.2f}" for o in _ if o.delivery)' -f orders.jsonl
#102 Linus: large Pepperoni $18.00
#103 Grace: small Hawaiian $10.00
#105 Margaret: medium Pepperoni $14.00
#106 Dennis: large Four Cheese $19.00
#108 Ken: large Meat Lovers $21.00
#109 Hedy: medium Veggie $13.50
Or build brand-new JSON objects on the fly. These are the big spenders:
% jello -S '({"who": o.name, "pie": o.pizza} for o in _ if o.price > 18)' -f orders.jsonl
{"who":"Dennis","pie":"Four Cheese"}
{"who":"Ken","pie":"Meat Lovers"}
{"who":"Alan","pie":"Pepperoni"}
Each line is a new JSON object, so the output is still valid JSON Lines. Notice how jello never needed to hold the whole file in memory to do any of this.
Loops and yield
When a one-liner isn’t enough, write a regular for loop and yield each result. One input can turn into many outputs. Let’s give every topping its own line, for the kitchen:
% jello -S '
for o in _:
for topping in o.toppings:
yield {"order": o.id, "topping": topping}
' -f orders.jsonl
{"order":101,"topping":"basil"}
{"order":102,"topping":"pepperoni"}
{"order":102,"topping":"extra cheese"}
{"order":103,"topping":"ham"}
{"order":103,"topping":"pineapple"}
{"order":104,"topping":"peppers"}
<snip>
You can also keep some state as you go. Here’s a running total for the till:
% jello -S '
till = 0
for o in _:
till += o.price
yield {"id": o.id, "price": o.price, "till": till}
' -f orders.jsonl
{"id":101,"price":12.5,"till":12.5}
{"id":102,"price":18.0,"till":30.5}
{"id":103,"price":10.0,"till":40.5}
{"id":104,"price":17.5,"till":58.0}
{"id":105,"price":14.0,"till":72.0}
{"id":106,"price":19.0,"till":91.0}
{"id":107,"price":9.0,"till":100.0}
{"id":108,"price":21.0,"till":121.0}
{"id":109,"price":13.5,"till":134.5}
{"id":110,"price":18.5,"till":153.0}
Note: queries can now use yield and return even without -S. More on that in Part 2.
Open the oven: live streams
Files are nice, but streaming really shines when the data never stops. Fire up oven.py and pipe it into jello:
% python3 oven.py | jello -S
{"id":1001,"time":"17:24:16","name":"Guido","pizza":"Hawaiian","size":"small","toppings":[],"price":11.0,"delivery":true}
{"id":1002,"time":"17:24:17","name":"Dennis","pizza":"Margherita","size":"large","toppings":["extra cheese","anchovies"],"price":18.0,"delivery":true}
{"id":1003,"time":"17:24:18","name":"Guido","pizza":"Four Cheese","size":"small","toppings":["extra cheese","olives"],"price":15.0,"delivery":false}
{"id":1004,"time":"17:24:19","name":"Margaret","pizza":"Hawaiian","size":"medium","toppings":["extra cheese","anchovies"],"price":17.0,"delivery":false}
{"id":1005,"time":"17:24:20","name":"Barbara","pizza":"Meat Lovers","size":"large","toppings":[],"price":19.0,"delivery":true}
{"id":1006,"time":"17:24:20","name":"Hedy","pizza":"Veggie","size":"small","toppings":["extra cheese"],"price":11.5,"delivery":true}
{"id":1007,"time":"17:24:21","name":"Grace","pizza":"Veggie","size":"medium","toppings":["anchovies"],"price":14.5,"delivery":true}
^C
Each order shows up the moment it comes out of the oven, about once a second. Press Ctrl-C when you’ve seen enough. Let’s make it a little easier on the delivery drivers:
% python3 oven.py | jello -Sr '(f"{o.time} {o.name:<8} {o.size:<6} {o.pizza:<12} ${o.price:>5.2f}" for o in _ if o.delivery)'
17:24:21 Alan medium Margherita $13.50
17:24:22 Margaret small Hawaiian $14.00
17:24:23 Barbara small Margherita $10.50
17:24:24 Ada medium Margherita $12.00
17:24:25 Dennis large Meat Lovers $22.00
17:24:26 Hedy medium Margherita $12.00
17:24:27 Ada large Pepperoni $18.50
17:24:27 Ken small Hawaiian $14.00
^C
Since jello only pulls the next order when your query asks for it, you can also stop early. itertools.islice() takes the first three orders, and then jello and the oven both stop on their own:
% python3 oven.py | jello -S '
import itertools
itertools.islice(_, 3)
'
{"id":1001,"time":"17:24:28","name":"Alan","pizza":"Pepperoni","size":"medium","toppings":["olives","extra cheese"],"price":17.0,"delivery":true}
{"id":1002,"time":"17:24:29","name":"Hedy","pizza":"Margherita","size":"small","toppings":["olives"],"price":10.5,"delivery":true}
{"id":1003,"time":"17:24:30","name":"Ken","pizza":"Hawaiian","size":"large","toppings":[],"price":17.0,"delivery":true}
Or wait for something specific. next() returns the first match, so this one waits for the first large Meat Lovers, prints a message, and exits. That’s handy for “tell me when this happens” scripts:
% python3 oven.py | jello -Sr '
o = next(o for o in _ if o.pizza == "Meat Lovers" and o.size == "large")
f"Order #{o.id} for {o.name} is the first large Meat Lovers!"
'
Order #1008 for Ken is the first large Meat Lovers!
Note: your orders will be different, since the oven is random. That’s half the fun.
Totals at the end
Sometimes you want one answer from the whole stream. If your query returns a dict or a number instead of an iterator, jello prints it just once. For totals like these, that happens when the stream ends, since the query has to read every order first. Which pizza is the most popular?
% jello -S '
import collections
collections.Counter(o.pizza for o in _)
' -f orders.jsonl
{"Margherita":2,"Pepperoni":3,"Hawaiian":1,"Veggie":2,"Four Cheese":1,"Meat Lovers":1}
Streaming output is always compact, but nothing stops you from piping it into another jello to pretty print it:
% jello -S '
import collections
collections.Counter(o.pizza for o in _)
' -f orders.jsonl | jello
{
"Margherita": 2,
"Pepperoni": 3,
"Hawaiian": 1,
"Veggie": 2,
"Four Cheese": 1,
"Meat Lovers": 1
}
And how many orders had pepperoni on them?
% jello -S 'sum(1 for o in _ if "pepperoni" in o.toppings)' -f orders.jsonl 4
Raw text with -SR
Not everything speaks JSON. Add -R and each input line arrives as a plain string, without its line ending. That turns jello into a line-by-line text processor with all of Python behind it.
ping is a great example: replies trickle in once a second, and the output looks a little different on every OS. This query pulls out the time with a regular expression and draws a bar chart as the replies come in:
% ping -c 6 1.1.1.1 | jello -SRr '
import re
for line in _:
m = re.search(r"time[=<]([\d.]+)", line)
if m:
ms = float(m.group(1))
yield f"{ms:6.1f} ms " + "#" * round(ms)
'
24.4 ms ########################
23.6 ms ########################
24.4 ms ########################
23.4 ms #######################
28.0 ms ############################
24.1 ms ########################
Note: on Windows, use
ping -n 6 1.1.1.1. The same query reads both thetime=12 msandtime=12msstyles.
Here’s one more. Run this in any git repository to turn your commit history into JSON Lines:
% git log --oneline -n 5 | jello -SR '
for line in _:
sha, message = line.split(" ", 1)
yield {"sha": sha, "message": message}
'
{"sha":"6ec887e","message":"Merge pull request #80 from kellyjonbrazil/stream-raw-input"}
{"sha":"5e46d22","message":"Document -R in streaming mode"}
{"sha":"b2dba82","message":"Support -R in streaming mode"}
{"sha":"b60a240","message":"Merge pull request #79 from kellyjonbrazil/streaming-mode"}
{"sha":"2919de6","message":"Update copyright date"}
Note: this is just a taste. For real work with git history, the
git-logparsers in jc turngit logoutput into JSON with every field (author, email, date, message, and file stats with--stat), andjc --git-log-sstreams it straight intojello -S. I wrote about them in Easily Convert git log Output to JSON.
Peek at the shape with -Ss
Not sure what fields you’re dealing with? -s works in streaming mode too. It prints the same grep-able schema it would for the whole list, one item at a time:
% jello -Ss -f orders.jsonl
_ = [];
_[0] = {};
_[0].id = 101;
_[0].time = "18:02";
_[0].name = "Ada";
_[0].pizza = "Margherita";
_[0].size = "medium";
_[0].toppings = [];
_[0].toppings[0] = "basil";
_[0].price = 12.5;
_[0].delivery = false;
_[1] = {};
_[1].id = 102;
_[1].time = "18:04";
<snip>
Since it streams, you can point it at a huge file (or a live stream) and start reading the schema right away.
More to come
So there you have it: streaming in jello! To recap, -S reads JSON Lines one at a time, _ is an iterator you loop over with generator expressions or yield, a query that returns a single value instead of an iterator (like the Counter totals) prints it just once, -R gives you raw text lines, and -s streams the schema.
In Part 2 we’ll go deeper: following log files with tail -f and Get-Content -Wait, rolling averages and windows over a stream, helper functions in .jelloconf.py, and pairing jello with the streaming parsers in jc. Here’s a sneak peek (Linux and macOS):
% ping -c 4 1.1.1.1 | jc --ping-s | jello -Sr '(f"seq {p.icmp_seq}: {p.time_ms} ms" for p in _ if p.type == "reply")'
seq 1: 23.8 ms
seq 2: 22.5 ms
seq 3: 22.0 ms
seq 4: 22.5 ms
What are you going to stream first? Let me know your favorite use cases, and I’ll try to work them into the next post. More to come!