Jon Jon - 4 months ago 48
jQuery Question

Generate JSON with Random Data

I"m using chance.js to help me generate some random data. It works really well, and I'd like to use this data to output random JSON objects.

Here's the structure I'm after:

{
"users": [
{
"Name": "John Smith",
"Fname": "John",
"Lname": "Smith",
"Email": "john.smith@acmemedia.com",
},

...etc
}


I have chance.js working in a jsFiddle, but I'm not sure how to output JSON data with the
chance.js
functions.

$(function() {
$("div[data]").each(function() {
var data = $(this).attr("data");
var chance = new Chance(Math.Random);
$(this).append(chance[data]());
});
});


http://jsfiddle.net/5Lcfz838/4/

The chance.js documentation is available here: http://chancejs.com/

Answer

Here is an array of 10 random objects:

var arr = new Array(10).fill().map(function() {
    return {
        first: chance["first"](),
        last: chance["last"](),
        email: chance["email"](),
        city: chance["city"](),
        state: chance["state"](),
    };
});

var json = JSON.stringify({ users: arr }); // as you asked for json
console.log(json);
<script src="https://cdnjs.cloudflare.com/ajax/libs/chance/0.5.6/chance.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments