Home > Software design >  How to find and replace a specific string in a json file with python
How to find and replace a specific string in a json file with python

Time:12-06

With a python program, I saved a ics file to a json one.The json file contains calendar info. My purpose is to replace a few specific strings (hours) by different ones (Keywords). basically 8:00 to Meeting1 ; 9:00 to Meeting 2 and so on. The Json content looks something like this 11/18/21 09:00 UTC-12/19/25 09:45 UTC Meeting-boss: - None. This being done by a python program would probably be to painful to change so I have to work with that. This is the python program that parses the ics file into a json one :


from datetime import datetime, timedelta, timezone
import icalendar
from dateutil.rrule import *
f = open('myschool.json', 'w')

def parse_recurrences(recur_rule, start, exclusions):
    """ Find all reoccuring events """
    rules = rruleset()
    first_rule = rrulestr(recur_rule, dtstart=start)
    rules.rrule(first_rule)
    if not isinstance(exclusions, list):
        exclusions = [exclusions]
        for xdate in exclusions:
            try:
                rules.exdate(xdate.dts[0].dt)
            except AttributeError:
                pass
    now = datetime.now(timezone.utc)
    this_year = now   timedelta(days=60)
    dates = []
    for rule in rules.between(now, this_year):
        dates.append(rule.strftime("%D %H:%M UTC "))
    return dates

icalfile = open('myschool.ics', 'rb')
gcal = icalendar.Calendar.from_ical(icalfile.read())
for component in gcal.walk():
    if component.name == "VEVENT":
        summary = component.get('summary')
        description = component.get('description')
        location = component.get('location')
        startdt = component.get('dtstart').dt
        enddt = component.get('dtend').dt
        exdate = component.get('exdate')
        if component.get('rrule'):
            reoccur = component.get('rrule').to_ical().decode('utf-8')
            for item in parse_recurrences(reoccur, startdt, exdate):
                print("{0} {1}: {2} - {3}\n".format(item, summary, description, location), file = f)
        else:
            print("{0}-{1} {2}: {3} - {4}\n".format(startdt.strftime("%D %H:%M UTC"), enddt.strftime("%D %H:%M UTC"), summary, description, location), file = f)
icalfile.close()

I have no idea how to this. The json could be a txt file if it makes things easier btw. All help appreciated :)

CodePudding user response:

I think you can use the "re" package (python regular expression) to do it and then you can use the method replace to replace the targeted string with the needed string

you can read more about the re module here https://docs.python.org/3/library/re.html

and this site will really help you to search through the JSON file and find the target string https://pythex.org/

CodePudding user response:

Your code is a bit hard to follow without having an example icalendar component along side the current json output, as well as your intended json output. If I am interpreting your code correctly, it looks like you are constructing your json by formatting the data retrieved from the icalendar component using component.get(). If this is correct, you should be able to replace the time portion (8:00 and 9:00 in your example) with "Meeting 1" and "Meeting 2" within the variable that holds this string when you first extract it from the icalendar file. You could then assemble your json from the strings as your currently are, since the change you would like to make would have be accomplished before constructing your json file.

For example: if startdt = component.get('dtstart').dt holds the string extracted from icalendar corresponding to "11/18/21 09:00", you would use either regex or something like string splitting to remove "09:00" and add "Meeting 2". Once the variable startdt is modified to have the data you want, your json should then inherit these changes.

assuming startdt holds the string which supplies date and time to your json (EX: "11/18/21 09:00") you could use the following code to change the string to "11/18/21 Meeting 2".

# import regex library
import re

# takes place of startdt = component.get('dtstart').dt in your code to make example easier.
startdt = "11/18/21 09:00"

# uses regex patter that looks for 2 digits, then ":" followed by 2 digits,
#then replaces the string that matches that pattern with "Meeting 2"
startdt = startdt.replace(re.search('\d{2}:\d{2}', startdt)[0], "Meeting 2")

print(startdt)

You don't specify how you decide how to name each meeting during the replacement, but you can just pass whatever name you want to the startdt.replace() line, rather than the hardcoded "Meeting 2" in the example.

  • Related