What is the best way to save JSON data within HTML elements?

I want to enhance my FAQ by making it easily editable. Currently, the content can only be edited in the HTML file. I am looking to load all the information from a JSON file so that any changes or additions to questions and answers can be made directly in the JSON file. While I attempted to create a CRUD functionality for this purpose, it proved to be quite challenging for me. If anyone knows how to implement a CRUD system and is willing to explain it or provide a tutorial (where data is still loaded into HTML elements), I would greatly appreciate it.

On another note, I am trying to embed JSON objects in HTML elements. The <H2> tag will hold the category, while the question goes inside the <a></a> tags and the answer within <p></p> tags. Can someone guide me on the JavaScript code required for this task? My goal is to check the category and automatically populate all questions related to that category from the JSON file in their respective places. Despite multiple attempts and research efforts, I have been unable to find a solution. Thank you in advance for your help.

JSON:

{
  "question": [
    {
      "id": 1,
      "question": "Quest",
      "answer": "Ans",
      "category": "Cat"
    },
    {
      "id": 2,
      "question": "Quest2",
      "answer": "Ans2",
      "category": "Cat2"
    },
    {
      "id": 3,
      "question": "Quest2",
      "answer": "Ans2",
      "category": "Cat2"
    },
    {
      "id": 4,
      "question": "Quest2",
      "answer": "Ans2",
      "category": "Cat2"
    }
  ]
}

HTML:

<ul id="algemeen" class="cd-faq-group">
    <li class="cd-faq-title"><h2>General</h2></li>
    <li>
    <a class="cd-faq-trigger" href="#0">Question</a>
    <div class="cd-faq-content">
    <p>Answer</p>
    </div> 
    </li>

Answer №1

It is recommended to avoid embedding JSON data directly into HTML elements. Instead, utilize AJAX to fetch the data, parse it, and dynamically generate the HTML structure using template literals.

function getJSON(callback) {
  const json = '{"question":[{"id":1,"question":"Quest","answer":"Ans","category":"Cat"},{"id":2,"question":"Quest2","answer":"Ans2","category":"Cat"},{"id":3,"question":"Quest3","answer":"Ans3","category":"Dog"},{"id":4,"question":"Quest24","answer":"Ans4","category":"Wolf"}]}';
  callback(json);
}

function sortByCategory(data) {
  return data.reduce((obj, c) => {
    const { category, ...rest } = c;
    obj[category] = obj[category] || [];
    obj[category].push(rest);
    return obj;
  }, {});
}

// Generates HTML for each question/answer pair
function buildQuestionHTML(arr) {
  
  // Iterate over the array of category objects
  return arr.map(el => {

    // Create HTML for the question/answer pair
    return `
      <li class="block">
        <a class="cd-faq-trigger" href="${el.id}">${el.question}</a>
        <div class="cd-faq-content">
          <p>${el.answer}</p>
        </div> 
      </li>
    `

  }).join('');
}

// Generates HTML for all categorised data
function buildPageHTML(data) {
 
  // Iterate over the categorised data
  return Object.keys(data).reduce((acc, c) => {
    
    // Get HTML for the question/answer pairs
    const questionHTML = buildQuestionHTML(data[c]);
    
    // Construct HTML for the category and
    // add the category name, and question/answer HTML
    const html = `
      <li class="cd-faq-title">
        <h2>${c}</h2>
      </li>
      ${questionHTML}
    `;
    acc.push(html);
    return acc;

  }, []).join('');
}

function displayQuestions() {
 
  // Fetch the data
  // Typically a server call would retrieve JSON data
  getJSON(function (json) {

    // Parse the retrieved data
    const questions = JSON.parse(json).question;
    
    // Sort data by category
    const categoryData = sortByCategory(questions);

    // Locate the element where compiled data should be inserted
    const root = document.getElementById('algemeen');

    // Build the HTML content
    const html = buildPageHTML(categoryData);

    // Append HTML to the root element
    root.insertAdjacentHTML('beforeend', html);
  });
}

// invoke displayQuestions function
displayQuestions();
ul {
  list-style-type: none;
}

.cd-faq-title {
  text-transform: uppercase;
}

.block {
  background-color: #efefef;
  padding: 0.3em;
}
<ul id="algemeen" class="cd-faq-group">
</ul>

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

Absence of property persists despite the use of null coalescing and optional chaining

Having some trouble with a piece of code that utilizes optional chaining and null coalescing. Despite this, I am confused as to why it is still flagging an error about the property not existing. See image below for more details: The error message display ...

How to retrieve the value of an input field in Angular 2/Typescript without using ngModel

Currently, I'm utilizing Typescript in conjunction with Angular2, mirroring the structure of the Angular2 Tour of Heroes guide. There is a specific input field that I aim to associate a change event with, triggering custom logic whenever the value wi ...

The view has no access to $scope but the controller does

I need to display the iso code using a $scope when selecting a country from a list. The list of countries is fetched through a $http call in a factory and then stored in a scope. ///////// get countries //////////////// tableFactory.getCountries().then(f ...

Is it possible to utilize Ajax submit requests within a (function($){...}(jQuery)); block?

As a PHP developer with some knowledge of JavaScript, I am currently using AJAX to send requests to the server. I recently came across the practice of enclosing all code within an anonymous JavaScript function like: (function($){ //code here }(jQuery)). Fo ...

Looking for assistance in using JavaScript to determine the percentage of a DIV's width in pixels

Using PHP, I am generating boxes whose width is set to 100% of a container in CSS. Now, I want to determine the equivalent pixel value of that box... HTML <div class="masonry" > <? while($row = $stmt->fetch()){ ?> <div class="i ...

Methods for delivering static resources on multiple routes in Express JS

Is there a way to effectively serve static resources for all routes in Express JS? I attempted to serve files with static resources using the following code snippet: app.use(Express.static(`${this.PATH}`)); app.use(Cors()); app.use(Express.json()); app.g ...

How to Convert Python Lists into JavaScript?

octopusList = {"first": ["red", "white"], "second": ["green", "blue", "red"], "third": ["green", "blue", "red"]} squidList = ["first", "second", "third"] for i in range(1): squid = random.choice(squidList) octopus = random. ...

What are some ways to restrict dynamic form submissions?

$(document).ready(function(){ var i = 1; $('#add').click(function(){ if(i < 5){ i++; $('#dynamic_field').append('<tr id="row'+i+'"><td><div class="form-group">& ...

bing translator API: the variable text is translated with no content

I'm encountering an issue while working with javascript and PHP. The PHP code seems to run fine until it reaches the $curlResponse variable. From there onwards, all the subsequent variables ($xmlObj, $translatedStr, $translatedText) appear to be empty ...

Restore radio input functionality with a transparent method

I've experimented with various methods, including traditional form reset techniques and jQuery solutions from different sources on the internet without success. Snapshot: The Objective: I am working on a sortable list where users are required to ra ...

Generating an order prior to payment being made by the customer

When a user selects a product and clicks the pay button, they are redirected to Stripe where a new order is created. However, if the user changes their mind and cancels the payment during the Stripe checkout process, the order has already been created. How ...

Notify the user with a message that our support is limited to Chrome, Firefox, and Edge browsers when utilizing Angular

How can I display a message stating that we only support Chrome, Safari, Firefox, and Edge browsers conditionally for users accessing our site from other browsers like Opera using Angular 10? Does anyone have a code snippet to help me achieve this? I atte ...

Determining light sources for unique shapes using Three.js

After creating a custom geometry and successfully using geometry.computeFaceNormals() to achieve correct lighting, I encountered an issue when attempting to animate the geometry. Even though I call geometry.computeFaceNormals() within the animation loop, t ...

What is the correct way to define a function parameter when using AngularJS Emit?

I've been exploring the emit feature in AngularJS and had a question about passing a function as an argument. In the Parent Controller: $scope.$on("getChildFunction", function(event, func) { console.log("The function is...", func); }) In the Ch ...

Retrieve the JSON data from an AJAX request

I am a beginner in the world of AJAX and JavaScript. In one of my projects, I need to retrieve a JSON object in my JavaScript file. I have utilized spray-json library which displays the JSON object at this URL: http://localhost:8081/all-modules { "statu ...

What is the best way to extract information from a Django database and save it in a JSON file on my personal computer

I recently developed a school management website for a local institution near my residence, utilizing Django as the backend framework. I have successfully stored student details in the Django database. My next goal is to extract all the data from the Djang ...

Node is currently posing a challenge for the installation of packages

I am currently facing an issue while setting up my raspberry pi 3. I am attempting to install and execute a node code, but I encountered a problem during the installation of packages using npm. After trying multiple times with different versions of node ( ...

Dynamic x-axis movement with interactive Google Line Chart functionality

I am struggling with implementing Google charts, After reviewing Real-time changing point chart with Google Charts, I realized it is not providing the solution I need. I aim to achieve a similar result as shown in this example: Is there a method for me t ...

Create object keys without relying on any ORM or database management systems like mongoose or mongodb

Exploring a Mongoose Object: recipe = { "ingredients": [ { "_id": "5fc8b729c47c6f38b472078a", "ingredient": { "unit": "ml", "name" ...

HTML code is not displayed within the ng-template

After passing JSON data in the correct format from my Laravel controller, I'm trying to display it recursively using Angular. However, the HTML inside ng-template is not being rendered. What could be the issue? Note: I've replaced the default An ...