How to find and replace a specific string in a json file with python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SwortClash
    New Member
    • Dec 2021
    • 1

    #1

    How to find and replace a specific string in a json file with python

    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 :
    Code:
    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 :)
  • Vanisha
    New Member
    • Jan 2023
    • 26

    #2
    To find and replace a specific string in a JSON file using Python, you can follow these steps:

    1.Read the JSON file into a Python object using the json.load() function.
    import json

    with open('file.json ', 'r') as f:
    data = json.load(f)
    2.Use a loop to iterate over the data and replace the specific string with the desired new string.
    old_str = 'old string'
    new_str = 'new string'

    for item in data:
    if isinstance(item , dict):
    for key, value in item.items():
    if value == old_str:
    item[key] = new_str
    elif isinstance(item , list):
    for idx, value in enumerate(item) :
    if value == old_str:
    item[idx] = new_str
    This code checks if each item in the JSON data is a dictionary or a list, and then searches for the old string within the items. If the old string is found, it is replaced with the new string.

    3.Write the modified data back to the JSON file using the json.dump() function.
    with open('file.json ', 'w') as f:
    json.dump(data, f)
    This will overwrite the original JSON file with the modified data.

    If you're looking to improve your coding skills or learn new technologies, join Cetpa Infotech.
    Check out our website for more information.

    Comment

    Working...