1

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/

Jon
  • 3,154
  • 13
  • 53
  • 96

1 Answers1

6

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 }, null, 2); // 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>
lorond
  • 3,856
  • 2
  • 37
  • 52
  • 1
    I've updated answer with json indentation. For more details look at this answer: http://stackoverflow.com/questions/4810841/how-can-i-pretty-print-json-using-javascript – lorond Jul 20 '16 at 17:12