e2nIEE / pandapower

Convenient Power System Modelling and Analysis based on PYPOWER and pandas
https://www.pandapower.org
Other
881 stars 484 forks source link

save pandapower net as JSON file #4

Closed lthurner closed 7 years ago

lthurner commented 7 years ago

The pickle files can only be read from python, so it would be helpful to have a possibility to save pandapower networks in an universally readable format such as JSON.

jhmenke commented 7 years ago

here is sample code to convert to json. i didn't implement from_json though.

import pandapower as pp
import pandas as pd
import numbers
import logging
import json

def to_json(net, filename):
    json_string = "{"
    for k in sorted(net.keys()):
        if k[:6] == "_empty":
            continue
        if k in ["std_types", "_mpc_last_cycle"]:
            continue
        if isinstance(net[k], pd.DataFrame):
            json_string += '"%s":%s,' % (k, net[k].to_json())
        elif isinstance(net[k], bool):
            json_string += '"%s":%s,' % (k, "true" if net[k] else "false")
        elif isinstance(net[k], str):
            json_string += '"%s":"%s",' % (k, net[k])
        elif isinstance(net[k], numbers.Number):
            json_string += '"%s":%s,' % (k, net[k])
        elif net[k] is None:
            json_string += '"%s":null,' % net[k]
        else:
            logging.error("could not detect type of %s: %s" % (k, net[k]))
    with open(filename, "w") as text_file:
        text_file.write(json_string[:-1] + "}\n")
jhmenke commented 7 years ago

Added, tested and will be released in pandapower 1.2