Random String Generation and Email Extraction with JSON Serialization

  • Share this:

Code introduction


This code generates a random string, then extracts email addresses from a given text, and finally serializes the data containing the random string and extracted emails into JSON format.


Technology Stack : Python built-in libraries: datetime, re, json, random, string

Code Type : Function

Code Difficulty : Intermediate


                
                    
import datetime
import re
import json
import random
import string

def generate_random_string(length=10):
    return ''.join(random.choices(string.ascii_letters + string.digits, k=length))

def extract_emails(text):
    email_pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
    return re.findall(email_pattern, text)

def serialize_data(data):
    return json.dumps(data, ensure_ascii=False, indent=4)

def main():
    random_string = generate_random_string(15)
    text_with_emails = "Please contact us at example@example.com for more information."
    found_emails = extract_emails(text_with_emails)
    data_to_serialize = {
        "random_string": random_string,
        "emails": found_emails
    }
    serialized_data = serialize_data(data_to_serialize)
    return serialized_data

print(main())