62 lines
1.5 KiB
Python
62 lines
1.5 KiB
Python
#!/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
|
||
# they’ll 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)
|
||
|
||
# Pretty‑print to stdout
|
||
json.dump(out, sys.stdout, indent=2, ensure_ascii=False)
|
||
print() # add final newline
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main() |