changed handling of json, to allow python to read (MESSY CODE AHEAD!)