Convert JSON to .ics (Python) -
i trying convert json file icalendar file. supervisor suggested using 2 functions convertto(data) (which converts json string) , convertfrom(data) (which converts string json; not sure of purpose of function).
my current approach uses lot of refactoring , multiple functions.
#returns string def __convert(data): convstr = __convertto(data) convstr = __fields(convstr) return convstr #convert json string def __convertto(data): str = "" + data return str #takes string arg (prev converted json) split useful info def __fields(data) ######### icalstr = __icaltemplate(title, dtstart, uid, remtype, email) return icalstr # def __icaltemplate(title, dtstart, uid, remtype, email): icstempstr = "begin:vevent\n dtstart:" + dtstart + "\nuid:" + uid + "\ndescription:" + desc + "\nsummary:" + title if remtype not none icstempstr += "\nbegin:valarm\naction:" + remtype + "description:this event reminder" if remtype email icstempstr += "\nsummary:alarm notification\nattendee:mailto:" + email icstempstr += "\nend:valarm" return icstempstr any hints or suggestions helpful. aware code needs lot of work.
this isn't intended complete answer, longer tip.
there's python idiom helpful in building strings, potentially large ones. it's easier see example explain:
>>> template = 'a value: {a}; b value: {b}' >>> data = {'a': 'spam', 'b': 'eggs'} >>> template.format(**data) 'a value: spam; b value: eggs' this idiom has number of advantages on string concatenation , eliminate need function altogether if write template correctly. optional inserts could, example, given values of ''. once format ical template correctly, it's matter of retrieving right data points json... , if name template insert points same have in json, might able conversion in 1 step. bit of planning, final answer simple as:
import json template = 'full ical template {insert_point} spec goes here' data = json.jsondecoder().decode(your_json_data) ical = template.format(**data) to quick (and different) interpreter example:
>>> import json >>> decoder = json.jsondecoder() >>> json_example = '{"item_one" : "spam", "item_two" : "eggs"}' >>> template = 'item 1: {item_one}\nitem 2: {item_two}' >>> print template.format(**decoder.decode(json_example)) item 1: spam item 2: eggs
Comments
Post a Comment