Populate HTML From JSON With jQuery - akFillFromJSON

File Size: 17.1 KB
Views Total: 1716
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
Populate HTML From JSON With jQuery - akFillFromJSON

ak-FillFromJSON is a jQuery plugin for populating HTML elements, attributes, links, form fields, and repeatable templates from JavaScript objects or JSON data.

It maps JSON keys to matching CSS classes in your markup, and it can also render arrays of objects with cloned templates, conditional field wrappers, callbacks, incremental loading, and value formatting.

See Also:

How to use it:

1. Insert jQuery and the akFillFromJSON.min.js file into your HTML page.

<script src="/path/to/jquery.min.js"></script>
<script src="/path/to/akFillFromJSON.min.js"></script>

2. Create the HTML markup. The plugin uses field names from your data to find matching elements in the target container.

<div id="myPage">
  <div class="firstNameDiv">
    First Name:
    <span class="firstNameVal"></span>
  </div>

  <div class="lastNameDiv">
    Last Name:
    <span class="lastNameVal"></span>
  </div>
</div>

For a field named firstName, .firstNameVal receives the value. .firstNameDiv is shown when the field has a value, while .not-firstNameDiv is shown when the value is empty.

3. Pass your data to the plugin through the data option.

$("#myPage").akFillFromJSON({
  data: {
    firstName: "jQuery",
    lastName: "Script"
  }
});

4. Use the following field-binding classes to control where each value is written.

  • .[field]Val: Populates the content of a standard HTML element.
  • .[field]Div: Shows the element when the field has a value and hides it when the field is empty.
  • .not-[field]Div: Shows the element when the field is empty and hides it when a value exists.
  • .[field]Val-link: Assigns the field value to an anchor's href.
  • .[field]Val-email: Creates a mailto: link.
  • .[field]Val-tel: Creates a tel: link.
  • .[field]Val-social: Builds a URL from data-base plus the field value.
  • .[field]Val-width: Assigns the field value to the element's CSS width.
  • .[field]Val-inpV: Assigns the field value to the value attribute.
  • .[field]Val-inpN: Assigns the value to the name attribute and adds it as a CSS class.
  • .[field]Val-title: Assigns the value to the title attribute.
  • .[field]Val-attr: Creates a data-[field] attribute.
  • .[field]Val-class: Adds the field value as a CSS class.

The plugin writes .[field]Val values to the src attribute on img, iframe, embed, and video elements. It writes the value to the data attribute on object elements.

<img
  class="avatarVal"
  data-path="/images/users/"
  data-append=".jpg"
  alt=""
>

<object
  class="documentVal"
  data-path="/files/"
></object>

5. Use HTML data-* attributes to change how values are matched or combined.

  • data-param: Binds an element to a field name without using the matching [field]Val class.
  • data-path: Prepends a path or URL segment to the field value.
  • data-append: Appends text to the field value after data-path is applied.
  • data-default: Supplies a fallback path for supported media, object, or link elements when the field value is empty.
  • data-base: Defines the base URL used by .[field]Val-social.
  • data-placeholder: Defines placeholder content for a field or a placeholder template for lazy-loaded records.
  • data-template: Defines the template used for each object in an array. It can reference HTML or an existing element such as #itemTemplate.
  • data-assign: Names the object key used to assign data-id to generated array items.
  • data-field: Identifies the field handled by an array holder.
  • data-format: Applies one of the supported date formats to a field value.
<a
  class="profileVal-social"
  data-base="https://example.com/users/"
>
  Profile
</a>

<img
  class="photoVal"
  data-path="/uploads/"
  data-append=".webp"
  data-default="/images/default-avatar.webp"
  alt=""
>

6. Convert and format values with the following helper classes.

  • .camelCase: Converts a string to camel case.
  • .pascalCase: Converts a string to Pascal case.
  • .alphaNumify: Keeps alphanumeric characters.
  • .slugify: Converts a string to a slug.
  • .toHTML: Converts line breaks to <br> and writes the result as HTML.
  • .toText: Converts HTML to plain text.
  • .toNumber-commas: Formats a number with locale-aware separators.
  • .toNumber-money: Formats a numeric value as money.
  • .toNumber-percent: Appends a percent sign.
  • .toColorBlock: Outputs a block that uses the field value as a background color.
  • .toFAicon: Outputs Font Awesome icon markup from the field value.
  • .toEmailLink: Converts an email address into a mailto: link.
<span class="usernameVal slugify"></span>
<div class="commentVal toHTML"></div>
<span class="priceVal toNumber-money"></span>
<span class="emailVal toEmailLink"></span>
$("#myPage").akFillFromJSON({
  data: {
    username: "jQuery Script",
    comment: "First line\nSecond line",
    price: 49.95,
    email: "[email protected]"
  }
});

7. Format date values with data-format.

<span class="createdAtVal" data-format="I"></span>
<span class="updatedAtVal" data-format="L"></span>
<span class="publishedAtVal" data-format="LL"></span>
  • I: Locale date such as 9/4/1986.
  • L: Two-digit month and day such as 09/04/1986.
  • LL: Long month format such as September 4, 1986.

8. Render arrays of objects with a repeatable item template.

<div id="productList" class="productsDiv" data-assign="id">
  <ul class="products-holder">
    <li class="products-item">
      <strong class="nameVal"></strong>
      <span class="descriptionDiv">
        -
        <span class="descriptionVal"></span>
      </span>
    </li>
  </ul>
</div>
$("#productList").akFillFromJSON({
  primaryKey: "products",
  data: [
    {
      id: 1,
      name: "Keyboard",
      description: "Compact mechanical keyboard"
    },
    {
      id: 2,
      name: "Mouse",
      description: "Wireless mouse"
    },
    {
      id: 3,
      name: "Monitor",
      description: "27-inch display"
    }
  ]
});

The plugin clones .products-item for each object and fills the fields inside each clone.

You can also provide a template explicitly with the template option or the data-template attribute.

<div id="products"
     class="productsDiv"
     data-template="#productTemplate">
</div>

<div id="productTemplate" class="products-item">
  <strong class="nameVal"></strong>
  <span class="priceVal toNumber-money"></span>
</div>

9. Limit the number of array records rendered at one time.

$("#productList").akFillFromJSON({
  primaryKey: "products",
  data: products,
  recordCount: 10,
  loadMoreLabel: "Show More"
});

When more records are available and lazyLoading is disabled, the plugin can add a Load More button. Set lazyLoading to true to load additional prepared records as the user scrolls.

$("#productList").akFillFromJSON({
  primaryKey: "products",
  data: products,
  recordCount: 10,
  lazyLoading: true
});

Full plugin options

  • readOnly (Boolean, default: false): Prevents matching form elements from receiving new values.
  • joinBy (String, default: ", "): Defines the separator for arrays of string values.
  • replaceArr (Array, default: []): Defines text replacements applied to string values.
  • lazyLoading (Boolean, default: false): Loads more array items during scroll when additional prepared records remain.
  • recordCount (Number or null, default: null): Limits the number of array records filled in one pass.
  • loadMoreLabel (String, default: "Load More"): Changes the text of the generated Load More button.
  • append (Boolean or Function, default: false): Keeps existing generated records before adding new records.
  • data (Object or Array, default: {}): Contains the JSON data used to fill the target element.
  • primaryKey (String, default: empty string): Identifies the field handled by the current plugin instance.
  • fromFieldEvent (Boolean, default: false): Prevents the optional toggleFieldRow() integration from running.
  • template (Object, jQuery object, selector, HTML, or null, default: null): Defines the item template used for arrays of objects.
  • beforeObj (Function): Runs before an array of objects starts rendering.
  • beforeFill (Function): Runs before each cloned array item receives its data.
  • callback (Function): Runs after each generated array item is inserted.
  • showLog (Boolean or Array, default: false): Controls diagnostic logging for supported fields and display operations.

replaceArr

Use replaceArr to replace text before a string value is written.

$("#myPage").akFillFromJSON({
  replaceArr: [
    ["old-value", "new-value"],
    ["draft", "published"]
  ],
  data: {
    status: "draft"
  }
});

append

Set append to true when a new array fill should keep existing generated items.

$("#productList").akFillFromJSON({
  primaryKey: "products",
  data: nextProducts,
  append: true
});

Callbacks

beforeObj

beforeObj(fieldName, $parentItem, dataObj, settings) runs before the plugin starts processing an array of objects.

$("#productList").akFillFromJSON({
  primaryKey: "products",
  data: products,
  beforeObj: function(fieldName, $parentItem, dataObj, settings) {
    if ($parentItem.hasClass("featuredProducts")) {
      settings.template = "#featuredProductTemplate";
    }
  }
});

beforeFill

beforeFill(fieldName, $itemToFill, dataObj, currentIndex, settings) runs before each cloned item is filled.

beforeFill: function(fieldName, $itemToFill, dataObj, currentIndex, settings) {
  $itemToFill.attr("data-position", currentIndex);
}

callback

callback(fieldName, $placedItem, dataObj, settings) runs after each generated item is inserted into the holder.

callback: function(fieldName, $placedItem, dataObj, settings) {
  $placedItem.addClass("is-ready");
}

API Methods

  • $("#holder").akFillFromJSON("clear"): Removes generated array items and resets the current record index.
  • $("#holder").akFillFromJSON("more"): Fills the next group of prepared array records.
  • $("#holder").akFillFromJSON("get"): Returns the current plugin instance associated with the holder.
  • instance.getInstance(): Returns the stored instance for the current holder.
  • instance.refresh(options): Clears the initialized holder and starts a new fill with the supplied options.
  • instance.clearItems(): Removes generated items and resets the array index.
  • instance.fillMore(): Fills the next batch of array items.
var fillInstance = $("#productList").akFillFromJSON("get");

fillInstance.clearItems();
fillInstance.fillMore();

Changelog:

2026-08-18

  • v2: Added array-of-object rendering, templates, placeholders, record limits, lazy loading, Load More support, callbacks, more value formatters, and public instance methods.

This awesome jQuery plugin is developed by akwebapps. For more Advanced Usages, please check the demo page or visit the official website.