views:

496

answers:

1

Hi,

I need a random object generator in JavaScript that generates a variety of objects with different fields and values. Any ideas where I can find such tool?

I need to generate random objects with various complexity.. My goal is to use JSON in order to serialize these objects and fuzz test my application http api.

+3  A: 
function createRandomObj(params,subobjs){
function getRandomString(size){
var p = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var f='';
for(var i=0;i<size;i++){
f+=p[Math.floor(Math.random()*p.length)];
}
}
var o={};
for(var i=0;i<params;i++){
var co;
var sd=Math.floor(Math.random()*(subobjs?6:5)
switch(sd){
case 0:
co=Math.floor(Math.random()*1000);
break
case 1:
co=Math.random();
break;
case 2:
co=Math.random()<0.5?true:false;
break;
case 3:
co=getRandomString(Math.floor(Math.random()*4)+4);
break;
case 4:
co=null;
break;
case 5:
co=createRandomObj(params,subobjs);
break;
}
o[getRandomString(8)]=co;
}
return o;
}

It will create a obj with X paramenters, all with a integer, float, string, boolean or null value.
I just made it :B

M28
Will it work if I set the value for one field to be an object:o[getRandomString(8)]=createRandomObj(5)I want to get more complex object generated.. something like:{"a":3,"b":{"c":4,"d":5}}
Gjorgji
Oh, sure, I'll implement it in a moment :)
M28
See second paramenter :), if it is true, it will make subobjects with using the same function and paramenters :)
M28