60 lines
1.9 KiB
Python
60 lines
1.9 KiB
Python
def merge_json(old_json, new_json):
|
|
# Überprüfen, ob new_json keine Timestamps enthält
|
|
if "timestamps" not in new_json:
|
|
return old_json
|
|
|
|
# Überprüfen, ob old_json keine Timestamps enthält
|
|
if "timestamps" not in old_json:
|
|
return new_json
|
|
|
|
# Schritt 1: Neue Timestamps prüfen und ggf. hinzufügen
|
|
for timestamp in new_json["timestamps"]:
|
|
if timestamp not in old_json["timestamps"]:
|
|
old_json["timestamps"].append(timestamp)
|
|
|
|
# Schritt 2: Neue Werte an den richtigen Positionen einfügen
|
|
for key, values in new_json["data"].items():
|
|
if key in old_json["data"]:
|
|
for i, timestamp in enumerate(new_json["timestamps"]):
|
|
index = old_json["timestamps"].index(timestamp)
|
|
if i < len(values):
|
|
if len(old_json["data"][key]) > index:
|
|
old_json["data"][key][index] = values[i]
|
|
else:
|
|
old_json["data"][key].append(values[i])
|
|
else:
|
|
old_json["data"][key] = [None] * len(old_json["timestamps"])
|
|
for i, timestamp in enumerate(new_json["timestamps"]):
|
|
index = old_json["timestamps"].index(timestamp)
|
|
if i < len(values):
|
|
if len(old_json["data"][key]) > index:
|
|
old_json["data"][key][index] = values[i]
|
|
else:
|
|
old_json["data"][key].append(values[i])
|
|
|
|
return old_json
|
|
|
|
# Beispielaufrufe
|
|
old_json1 = {
|
|
"timestamps": ["s", "e", "r"],
|
|
"data": {"foo": [1, 2, 4], "bar": [3, 4, 6]}
|
|
}
|
|
|
|
new_json1 = {}
|
|
|
|
merged_json1 = merge_json(old_json1, new_json1)
|
|
print(merged_json1)
|
|
|
|
old_json2 = {}
|
|
|
|
new_json2 = {
|
|
"timestamps": ["r", "p"],
|
|
"data": {"foo": [4, 4], "bar": [6, 7]}
|
|
}
|
|
|
|
merged_json2 = merge_json(old_json2, new_json2)
|
|
print(merged_json2)
|
|
|
|
|
|
merged_json2 = merge_json(old_json1, new_json2)
|
|
print(merged_json2) |