Driver Validate JSON

Demonstrates how to validate your JSON string that you include in your switch driver script.

Example Scripts

Copy
Validate JSON from String
import json

def valid_json(jsonstr):
    try:
        json.loads(jsonstr)
    except ValueError as e:
        return False
    return True

json_str = """
{
    "ModelNumber": "My Switch",
    "SerialNumber": "12455",
    "SettlingTimeSeconds": "50e-3",
    "Groups": [
        {
            "Name": "",
            "InputPorts": ["1", "2", "3", "4", "5", "6", "7", "8"],
            "OutputPorts": ["IN"],
            "Wavelengths": ["1350 nm", "1550 nm"]
        }
    ]
} """

print(valid_json(json_str))
Copy
Validate JSON from String
import json

def valid_json(jsonstr):
    try:
        json.loads(jsonstr)
    except ValueError as e:
        return False
    return True

json_str = """
{
    "ModelNumber": "My Switch",
    "SerialNumber": "12455",
    "SettlingTimeSeconds": "50e-3",
    "Groups": [
        {
            "Name": "SW1",
            "InputPorts": ["1", "2", "3", "4", "5", "6", "7", "8"],
            "OutputPorts": ["IN"],
            "Wavelengths": ["1350 nm", "1550 nm"]
        },
        {
            "Name": "SW2",
            "InputPorts": ["1", "2", "3", "4", "5", "6", "7", "8", "9"],
            "OutputPorts": ["IN 1", "IN 2", "IN 3", "IN 4"],
            "Wavelengths": ["1350 nm", "1550 nm"]
        }
    ]
} """

print(valid_json(json_str))
Copy
Validate JSON from Structure
import json

def valid_json(jsonstr):
    try:
        json.loads(jsonstr)
    except ValueError as e:
        return False
    return True

switch = {'Name': '',
         'InputPorts': ['1', '2', '3', '4', '5', '6', '7', '8'],
         'OutputPorts': ['IN'],
         'Wavelengths': ['1350 nm', '1550 nm']}

sw_list = [switch]
data_structure = {'ModelNumber': 'My Switch', 'SerialNumber': '12455', 'SettlingTimeSeconds': '50e-3', 'Groups': sw_list}
json_str = json.dumps(data_structure)
print(valid_json(json_str))
Copy
Validate JSON from Structure
import json

def valid_json(jsonstr):
    try:
        json.loads(jsonstr)
    except ValueError as e:
        return False
    return True

sw1 = {'Name': 'SW1',
       'InputPorts': ['1', '2', '3', '4', '5', '6', '7', '8'],
       'OutputPorts': ['IN']}
sw2 = {'Name': 'SW2',
       'InputPorts': ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
       'OutputPorts': ['IN 1', 'IN 2', 'IN 3', 'IN 4'],
       'Wavelengths': ['1350 nm', '1550 nm']}
sw_list = [sw1, sw2]
data_structure = {'ModelNumber': 'My Switch', 'SerialNumber': '12455', 'SettlingTimeSeconds': '50e-3', 'Groups': sw_list}
json_str = json.dumps(data_structure)
print(valid_json(json_str))