From 69c702fd5dc2b6f2a91e01b20b528a66976b12fb Mon Sep 17 00:00:00 2001 From: Thomas Bleher Date: Tue, 17 Mar 2026 14:40:20 +0100 Subject: [PATCH] osi2read: add json output option Add an option to output the data as JSON. This makes it easier to analyze the data with tools like `jq`, or pass it to other tools that want to consume OSI (and take only json as an input). --- osi3trace/osi2read.py | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/osi3trace/osi2read.py b/osi3trace/osi2read.py index a75bb9a..40d9421 100644 --- a/osi3trace/osi2read.py +++ b/osi3trace/osi2read.py @@ -1,12 +1,19 @@ """ -This program converts serialized osi trace files into a human readable txth file. +This program converts serialized osi trace files into a human readable output. + +Supported output formats: + txth - Human readable text (default) + json - JSON format (machine parsable, protobuf compatible) Example usage: python3 osi2read.py -d trace.osi -o myreadableosifile + python3 osi2read.py -d trace.osi --format json """ from osi3trace.osi_trace import OSITrace +from google.protobuf.json_format import MessageToJson import argparse +import json import pathlib @@ -14,7 +21,7 @@ def command_line_arguments(): """Define and handle command line interface""" parser = argparse.ArgumentParser( - description="Convert a serialized osi trace file to a readable txth output.", + description="Convert a serialized osi trace file to a readable txth or json output.", prog="osi2read", ) parser.add_argument( @@ -40,6 +47,15 @@ def command_line_arguments(): type=str, required=False, ) + parser.add_argument( + "--format", + "-f", + help="Output format.", + choices=["txth", "json"], + default="txth", + type=str, + required=False, + ) return parser.parse_args() @@ -52,12 +68,23 @@ def main(): trace = OSITrace(args.data, args.type) if not args.output: - path = pathlib.Path(args.data).with_suffix(".txth") + suffix = ".json" if args.format == "json" else ".txth" + path = pathlib.Path(args.data).with_suffix(suffix) args.output = str(path) with open(args.output, "wt") as f: - for message in trace: - f.write(str(message)) + if args.format == "json": + f.write("[\n") + first = True + for message in trace: + if not first: + f.write(",\n") + first = False + f.write(MessageToJson(message)) + f.write("\n]\n") + else: + for message in trace: + f.write(str(message)) trace.close()