Files
HP_InHand_IG502/code snippets/convertGetFormatToPostFormat.py
2026-03-10 13:22:03 -05:00

62 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Transform:
{
"<property>": [
{"ts": 123, "value": 10},
{"ts": 456, "value": 20},
...
],
...
}
into:
[
{"ts": 123, "values": {"<property>": 10}},
{"ts": 456, "values": {"<property>": 20}},
...
]
"""
import json
import sys
from collections import defaultdict
def transform(data: dict) -> list:
"""
Accepts a dict where each key is a property name and the value is a
list of {ts, value} objects. Returns a list of objects sorted by
timestamp, each with a 'values' dict that maps the property name to
its value for that timestamp.
"""
# Group values by timestamp first (so if you have several properties
# theyll be merged on the same ts).
grouped = defaultdict(dict)
for prop, items in data.items():
for item in items:
ts = item["ts"]
grouped[ts][prop] = item["value"]
# Build the final list, sorted by ts for deterministic order
result = [{"ts": ts, "values": grouped[ts]} for ts in sorted(grouped)]
return result
def main():
# Load JSON from stdin or a file
if len(sys.argv) > 1: # optional filename argument
with open(sys.argv[1], "r", encoding="utf-8") as f:
raw = json.load(f)
else:
raw = json.load(sys.stdin)
out = transform(raw)
# Prettyprint to stdout
json.dump(out, sys.stdout, indent=2, ensure_ascii=False)
print() # add final newline
if __name__ == "__main__":
main()