如何在html标签中存储JSON数据?

时间:2018-11-26 13:33:58

标签: javascript json

我正在制作一个常见问题解答,并希望使其更易于编辑。现在,只能在html文件中对其进行编辑。我想从JSON文件中加载所有信息,以便在需要更改或添加问题或答案时可以编辑json文件。我想进行某种CRUD,但这对我来说似乎太困难了。如果可以使用它进行CRUD,并且有人可以向我解释如何做或给出一个很棒的教程(数据仍必须加载到html元素中)。

尽管如此,我还是试图将JSON对象存储在HTML元素中。在<H2>内部有类别。 <a></a>里面是问题,而<p></p>里面是答案。有人知道我必须为此使用什么javascript代码吗?我希望它检查类别,并将JSON文件中该类别的所有问题都放在正确的位置。我尝试了多种方法并尝试查找它,但都徒劳无功。预先感谢。

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>

1 个答案:

答案 0 :(得分:0)

我会避免在HTML元素中放置任何JSON,而是使用AJAX下载数据,解析数据,然后使用模板文字构建HTML结构。

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;
  }, {});
}

// Returns the question/answer HTML 
function buildQuestionHTML(arr) {
  
  // Iterate over the category array objects
  return arr.map(el => {

    // In each case return the question/answer HTML
    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>
    `

  // Making sure we join up the final array
  }).join('');
}

// Returns all the HTML from the categorised data
function buildPageHTML(data) {
 
  // Iterate over the categorised data
  return Object.keys(data).reduce((acc, c) => {
    
    // Get the question/answer HTML
    const questionHTML = buildQuestionHTML(data[c]);
    
    // Create the scaffold 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;

  // We're adding the HTML to an array so we need
  // to ensure we join it up into a string
  }, []).join('');
}

function displayQuestions() {
 
  // Get the data
  // This would normally be a call to your server which 
  // would return some JSON data
  getJSON(function (json) {

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

    // Get the root element where you want the compiled data to be added
    const root = document.getElementById('algemeen');

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

    // Add it to the root element
    root.insertAdjacentHTML('beforeend', html);
  });
}

// call displayQuestions
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>