import json
import datetime
# ---------------- INPUT DATA ----------------
data1 = {
"deviceID": "dh28dslkja",
"deviceType": "LaserCutter",
"timestamp": 1624445837783,
"location": "japan/tokyo/keiyō-industrial-zone/daikibo-factory-meiyo/section-1",
"operationStatus": "healthy",
"temp": 22
}
data2 = {
"device": {
"id": "dh28dslkja",
"type": "LaserCutter"
},
"timestamp": "2021-06-23T10:57:17.783Z",
"country": "japan",
"city": "tokyo",
"area": "keiyō-industrial-zone",
"factory": "daikibo-factory-meiyo",
"section": "section-1",
"data": {
"status": "healthy",
"temperature": 22
}
}
expected = {
"deviceID": "dh28dslkja",
"deviceType": "LaserCutter",
"timestamp": 1624445837783,
"location": {
"country": "japan",
"city": "tokyo",
"area": "keiyō-industrial-zone",
"factory": "daikibo-factory-meiyo",
"section": "section-1"
},
"data": {
"status": "healthy",
"temperature": 22
}
}
# ---------------- CONVERTERS ----------------
def convertFromFormat1(jsonObject):
parts = jsonObject["location"].split("/")
return {
"deviceID": jsonObject["deviceID"],
"deviceType": jsonObject["deviceType"],
"timestamp": jsonObject["timestamp"],
"location": {
"country": parts[0],
"city": parts[1],
"area": parts[2],
"factory": parts[3],
"section": parts[4]
},
"data": {
"status": jsonObject["operationStatus"],
"temperature": jsonObject["temp"]
}
}
def convertFromFormat2(jsonObject):
dt = datetime.datetime.strptime(
jsonObject["timestamp"],
"%Y-%m-%dT%H:%M:%S.%fZ"
)
timestamp = int(dt.timestamp() * 1000)
return {
"deviceID": jsonObject["device"]["id"],
"deviceType": jsonObject["device"]["type"],
"timestamp": timestamp,
"location": {
"country": jsonObject["country"],
"city": jsonObject["city"],
"area": jsonObject["area"],
"factory": jsonObject["factory"],
"section": jsonObject["section"]
},
"data": {
"status": jsonObject["data"]["status"],
"temperature": jsonObject["data"]["temperature"]
}
}
def main(jsonObject):
if "device" in jsonObject:
return convertFromFormat2(jsonObject)
else:
return convertFromFormat1(jsonObject)
# ---------------- TESTS ----------------
r1 = main(data1)
r2 = main(data2)
print("Format 1 OK:", r1 == expected)
print("Format 2 OK:", r2 == expected)
print("\nOUTPUT SAMPLE:")
print(json.dumps(r1, indent=2))