Monday, September 2, 2013

Random JSON Payload generator in Ruby

Here's a quick random JSON generator in Ruby for testing your code:

# Get a random hash of strings
def get_random_string(character_count)
  o =  [('a'..'z'),('A'..'Z')].map{|i| i.to_a}.flatten

  (0...character_count).map{ o[rand(o.length)] }.join
end

# Get random json payload, input is size of each field and number of fields
def get_random_json_payload(number_of_fields, field_size)
  fields = {}
  # Generate payload hash
  (1..number_of_fields).each do |field_number|
    fields['field_'+field_number.to_s] = get_random_string(field_size)
  end

  fields.to_json
end





puts get_random_json_payload(2,10)

The output will be like
{"field_1":"VUQZDpYRgA","field_2":"LtMQYvSZca"}



No comments:

Post a Comment