Revise the JSON format to be compatible with a JavaScript template library

My goal is to utilize JSON data for parsing a template using JavaScript. The Mustache library provides a solution as shown below:

var output = $("#output"); 

// template stored in JS var as a string
var templateString = '<div>'+
'<ul>'+
'  <li>{{first_name}} {{last_name}} goes by the username of: {{user_name}}</li>'+
'</ul>'+
'</div>';

// parse template stored in JS string var
var html = Mustache.render(templateString, jsonData);
output.append(html);

The issue at hand is that the JSON data I have does not conform to the required format for Mustache templates.

The expected JSON format by Mustache is as follows:

var jsonData2 = { 
"users":[
{  
    "id":"1",
    "user_name":"jasondavis",
    "first_name":"Jason",
    "last_name":"Davis",
    "is_admin":"1",
    "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/31b64e4876d603ce78e04102c67d6144?s=80&d=identicon&r=PG",
    "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/31b64e4876d603ce78e04102c67d6144?s=80&d=identicon&r=PG"
},
{  
    "id":"1702c3d0-df12-2d1b-d964-521becb5e3ad",
    "user_name":"Jeff",
    "first_name":"Jeff",
    "last_name":"Mosley",
    "is_admin":"1",
    "gravatar_id":"http:\/\/www.gravatar.com\/avatar\/5359bf585d11c5c35602f9bf5e66fa5e?s=80&d=identicon&r=PG",
    "gravatar_url":"http:\/\/www.gravatar.com\/avatar\/5359bf585d11c5c35602f9bf5e66fa5e?s=80&d=identicon&r=PG"
}
]};

Adjustments need to be made to the JSON data format to align with the Mustache template structure.

For more details and a demo, visit: http://jsfiddle.net/utgrLw96/25/

Answer №1

It was mentioned in a previous comment that your jsonData is not in JSON format, but rather a JavaScript object. You can easily adjust it using jQuery, as you are already utilizing it.

var usersArray = $.map(jsonData, function(value, index) {
    return [value];
});
var mustacheData = {users: usersArray};

However, this alone may not suffice. Your template is designed for a list of users, but is currently configured for just one user. To rectify this issue, your template should resemble the following:

var templateString = "
  <div><ul>
    {{#users}}
    <li>{{first_name}}{{last_name}} goes by the username of:{{user_name}}</li>
    {{/users}}
  <div><ul>
";

(Although this was previously mentioned, I included it in the answer as it now applies to the new data.)

View the corrected fiddle

Answer №2

I iterated over your jsonData by using the jQuery.each method, and I believe this code snippet will generate the desired outcome:

$.each(jsonData, function(key,val) {

     var html = Mustache.to_html(templateString, val);

     output.append(html);
});

Feel free to check out the revised code on jsfiddle.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Swap out a term in a sentence with an interactive span element in real-time

I'm struggling with a seemingly simple task, and I feel quite embarrassed that I can't seem to solve it. My goal is to identify words in a string that begin with '@' or '#' and change their color to blue. The string itself com ...

Jackson utilizes a bespoke JSON deserializer with a predefined configuration

Here's a simplified version of the code I'm working with. I have a JSON structure: { "content" : { "elements" : [ { "type" : "simple" }, { "type" : "complex", "content" : { ...

Adding data from a database into an object in PHP for temporary use during the loading process can be achieved by following

I'm a beginner in PHP and I have some code that retrieves category type data from a database. I want to temporarily store this data in a PHP object while the page is loading. Initially, I need to load all predefined data and then use it when a certain ...

Python - Converting JSON data into a CSV file

I need help with a script that reads JSON data from a file and then extracts specific content to populate a table. The challenge I'm facing is that the structure of the JSON data varies for different entries, making it difficult to map the fields accu ...

Utilize the datepicker function in jQuery version 1.6.3 to select a range of dates

I need help adding a jQuery datepicker to my JSP page for selecting a date range. Below is the current code I am working with. $(function() { $( "#createdAtFrom" ).datepicker({ defaultDate: "+1w", changeMonth: true, ...

What are some ways to provide the find() method in JavaScript with a specific search argument?

I've been exploring ways to search within an array while iterating through it. One method I stumbled upon is the find() method. Take a look at this example: var inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas&apos ...

Trouble arises when adding a .js script to the webpage

I'm feeling quite puzzled by this small piece of code, as it appears to be the simplest thing you'll come across today. Despite that, I can't help but seek guidance because I've been staring at it for what feels like an eternity and can ...

Implement a Selection Feature in Angular

Currently, I am working on an application where users can add new rows with the same fields. One of the requirements is to allow users to add an option to a select element. While I have successfully implemented this in jQuery, I am facing challenges integr ...

Guide to crafting a reply using nestjs exception filters with nestfastify

I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following mann ...

Running JavaScript code along with HTML elements extracted from a jQuery ajax callback

Alternatively, not exactly "executing," but rather updating a pre-existing function with a function returned in the response. Step 1 I have an HTML5 page detailing a specific location. The server-side includes a ColdFusion file called "MapFunction.cfm" ...

Manipulating JSON data in PHP - Rearrange values in a JSON file before displaying them

I am currently engaged in a research project focusing on the search results provided by Bing. As I am still relatively new to PHP, I could really use some assistance. I received help here yesterday which greatly benefitted me, prompting me to seek guidance ...

Using Python to convert JSON data to an Excel format

I need to convert a JSON file into an Excel sheet. To do this, I am using Python 3.8 along with the xlsxwriter library. Below is a snippet of the sample JSON data. { "companyId": "123456", "companyName": "Test&quo ...

Generate dynamic Bootstrap Carousel slides with unique hashtag URLs

I've been attempting to connect to various slides within a bootstrap carousel from a different page but have had no success. Here is an example of what I'm trying to achieve: <a href="services#slide2">Link to Slide 2</a> For refere ...

Using jQuery to display a div after a 2-second delay on my website, ensuring it only appears once and does not reappear when the page is refreshed or when navigating to a

I manage a website that includes a blog section. Every time someone visits the site, I want a popup window to appear. (To achieve this, follow these steps - Utilize jQuery for showing a div in 5 seconds) I would like this popup to only be displayed once ...

Navigating through pages using Jquery's show and hide functionality

How come my item is not returning? I used the .show() method on the item. <div id="back">< back</div> <div class="item">item</div> <div class="content">My content</div> $(function(){ $('.item').on(&apo ...

Changing a portion of a string into a java.util.Date

After posting DateTime as JSON, it gets transformed into "/Date(1512839439513)/" I am looking to simply convert this format to java.util.Date "/Date(1512839439513)/" needs to be converted to java.util.Date My attempt so far: String date = finalObject.g ...

Utilizing Google Maps API version 3 to display various groups of markers

I am encountering an issue while trying to plot fixed markers and a user position marker on a Google Map. I want to use different images for these markers, but something strange is happening. When the page loads, all fixed markers show up correctly initial ...

Troubleshooting problem with jwPlayer resizing in Firefox and Opera browsers

<script type="text/javascript" src="js/jwplayer/jwplayer.js"></script> <div id="myElement"">Loading the player...</div> <script type="text/javascript"> jwplayer("myElement").setup({ file: "video/mosk.mp4", ...

Issues with AJAX requests failing to fire with the latest version of jQuery

A small script I have checks the availability of a username in the database, displaying "taken" if it's already taken and "available" if it's not. The code below works perfectly with jQuery v1.7.2. However, I need to update it for jQuery v3.2.1. ...

Using the Angular translate filter within a ternary operator

I am currently working on translating my project into a different language. To do this, I have implemented the Angular Translate library and uploaded an external JSON file containing all the translations. Here is an example of how it looks: { "hello_wor ...