问题
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.
回答1:
function createRandomObj(fieldCount, allowNested)
{
var generatedObj = {};
for(var i = 0; i < fieldCount; i++) {
var generatedObjField;
switch(randomInt(allowNested ? 6 : 5)) {
case 0:
generatedObjField = randomInt(1000);
break;
case 1:
generatedObjField = Math.random();
break;
case 2:
generatedObjField = Math.random() < 0.5 ? true : false;
break;
case 3:
generatedObjField = randomString(randomInt(4) + 4);
break;
case 4:
generatedObjField = null;
break;
case 5:
generatedObjField = createRandomObj(fieldCount, allowNested);
break;
}
generatedObj[randomString(8)] = generatedObjField;
}
return generatedObj;
}
// helper functions
function randomInt(rightBound)
{
return Math.floor(Math.random() * rightBound);
}
function randomString(size)
{
var alphaChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var generatedString = '';
for(var i = 0; i < size; i++) {
generatedString += alphaChars[randomInt(alphaChars.length)];
}
return generatedString;
}
It will create a obj with X paramenters, all with a integer, float, string, boolean or null value.
I just made it :B
回答2:
You can use hasard library
Random variables and random nested objects manipulation in javascript
const h = require('hasard');
const randomInteger = h.integer({type: 'poisson', lambda: 4});
const randomString = h.string({
size: h.add(randomInteger, 5),
value: h.value('abcdefghijklmnopkrstuvw'.split(''))
});
const randomNumber = h.number([0, 100]);
const randomKeys = h.array({
size: randomInteger,
value: randomString
});
// we first define it, to use it as reference into randomObject
const randomValue = h.value();
const randomObject = h.object(
randomKeys,
randomValue
);
// And we set recursivity by setting his values afterward
randomValue.set([
randomString,
randomObject,
randomNumber,
randomInteger
]);
Results will looks like
[
{
"vbmujvv": "rfigcpcvpj",
"sjmcgvvk": 3,
"efdarehl": {
"odinthsuca": "rwjhmbfus",
"noihjtjen": 27.73332043042913,
"brspkaagb": "lnuiabcfd"
},
"febtungjhfokf": 49.28625818957401,
"eoemrkgi": {
"jkcuwrpsh": "ekjoltm",
"cincs": {
"fcovbwk": {
"whsgmjh": 48.00843935524626,
"agsjflef": 46.700796253998014
},
"ovkdfudgfm": 84.83383163217746,
"fpfetl": "djuvfjbjptf",
"kobmkstj": {
"wskgkkerk": 9,
"kvnptptek": 37.63655947554132,
"dsloun": 4
}
},
"krirwk": {
"sjgftomu": 51.663884142674775,
"hpjgibnli": 4
},
"pkhkgruls": "isuodwjrg"
},
"ortomnue": 71.71303423929236
}
]
DISCLAIMER i'm the author of hasard library
来源:https://stackoverflow.com/questions/2443901/random-object-generator-in-javascript