Generating JSON objects dynamically in JavaScript

September 26, 2015, 10:09 pm
Author: James Griffiths

Working with JSON provides front-end developers with many advantages over other data formats, least of which is the fact that it's a subset of the JavaScript language itself.

In this short tutorial we'll take you through dynamically generating a JSON object within JavaScript...

Let's say, for the sake of illustration, that we want to loop through a list of HTML elements and retrieve product data from which we will then use to create a JSON object for posting via AJAX.

Our HTML might look something like this:

<ul class="products-list">
    <li data-code="102462" 
        data-price="35">Sample product heading #1</li>
    <li data-code="792365"
        data-price="18">Sample product heading #2</li>
    <li data-code="258193" 
        data-price="24">Sample product heading #3</li>

With a little help from jQuery here's how we could create our JSON object:

var products           =   {"productData”:[]};

  var productCode      =   $(this).data('code'),
      productQuantity  =   $(this).data('quantity'),
      productPrice     =   $(this).data('price');

    "code": productCode, 

We could, if we felt so inclined, re-write our loop sequence like so, to help optimise the script a little further:

var products           =   {"productData”:[]};

    "code": $(this).data('code'), 

In both of the above examples we begin by defining our JSON object, followed by iterating through all of the list items where we retrieve the values from the appropriate data attributes which are then pushed into our JSON object as key/value pairs.

Nice and easy huh? Told you it would be a short tutorial!


« Return to Posts

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.