Random String Generator with JSON Output

  • Share this:

Code introduction


This function takes two arguments, the first must be of type string and the second must be a positive integer. The function generates a random string of length specified by the second argument and returns it in JSON format.


Technology Stack : random, string, json

Code Type : Function

Code Difficulty : Intermediate


                
                    
import random
import string
import json

def generate_random_string(length=10):
    return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(length))

def xxx(arg1, arg2):
    if not isinstance(arg1, str) or not isinstance(arg2, int):
        return "Invalid input types"
    
    if arg2 <= 0:
        return "The length must be a positive integer"
    
    random_string = generate_random_string(arg2)
    return json.dumps({"random_string": random_string})