簡體   English   中英

將 JSON 對象轉換為 html 字符串

[英]convert JSON object to html string

我有一個 JSON:

    const json = {
  "name": "superman",
  "place": "universe",
  "pets": [
    {
      "id": "1",
      "type": "dog",
      "name": "Drogo"
    },
    {
      "id": "2",
      "type": "cat",
      "name": "Cindy"
    }
  ]
};

要求是將其更改為 html 字符串,如下所示:

' <body><div>superman</div><div>universe</div><div><p>1</p><p>dog</p><p>Drogo</p><p>2</p><p>cat</p><p>Cindy</p></div></body> '

我寫了下面的函數來解決它。 基本上,我使用 Object.entries 遍歷 json 以獲得 [key, value] 對,然后將該值附加到 myStr,我的最終字符串變量。 但我不能保留這樣形成的字符串。

let myStr = ""; // initialize String
const printString = (o, myStr) => {
  if (typeof o === "string") {
    myStr += "<div>" + `${o}` + "</div><br>";
  }
  return myStr;
};
const getString = json => {
  for (let [key, value] of Object.entries(json)) {
    printString(value, myStr);
    if (Array.isArray(value)) {
      value.forEach(item => {
        printString(item, myStr);
      });
    }
  }
  return myStr;
};

const htmlString = "<body>" + getString(json) + "</body>";

console.log(htmlString);

我的邏輯需要一些幫助。 此外,我有幾個問題:

i) 如何編寫包含所有這些功能的 1 個函數,包括 myStr 變量,以便我的代碼是模塊化的 ii) 為什么 myStr 不能記住以前的字符串? iii) 在此類問題中,僅通過特定的 json 對象並對其進行迭代是明智的,還是應該有一個更通用的函數來檢查 json 中的對象、字符串或數組,然后相應地生成字符串?

您沒有在作為對象數組的屬性中添加項目,您可以使用Object.values()迭代這些值Object.values()加到<p>標簽。

此外,您沒有將printString()函數中形成的新字符串重新分配回myStr變量,因此生成的新字符串丟失了。

這是因為 string 是不可變的,將新字符串附加到舊字符串將創建字符串的新實例:

 const json = { name: "superman", place: "universe", pets: [ { id: "1", type: "dog", name: "Drogo" }, { id: "2", type: "cat", name: "Cindy" } ] }; let myStr = ""; // initialize String const printString = (o, myStr, tag) => { if (typeof o === "string") { myStr += `<${tag}> ${o} </${tag}>`; }else if(typeof o === "object"){ Object.values(o).forEach(val => myStr += `<${tag}> ${val} </${tag}>`); } return myStr; }; const getString = json => { for (let [key, value] of Object.entries(json)) { if (Array.isArray(value)) { myStr += "<div>" value.forEach(item => { myStr = printString(item, myStr, "p"); }); myStr += "</div>" }else{ myStr = printString(value, myStr, "div"); } } return myStr; }; const htmlString = "<body>" + getString(json) + "</body>"; console.log(htmlString);

它看起來有點難看但仍然有效,如果你知道你的數組有多深,那么我不會使用遞歸。

工作證明: https : //jsfiddle.net/bajuck9y/

JS

let html = '';
for (const key in json) {
  if (!Array.isArray(json[key])) {
    html += '<div>' + json[key] + '</div>'
  } else {
    html += '<div>';
    for (const item of json[key]) {
      for (const key2 in item) {
        html += '<p>' + item[key2] + '</p>'
      }

    }
    html += '</div>';

  }

}

或者,也許,這樣做?

 const json = { name: "superman", place: "universe", pets: [ { id: "1", type: "dog", name: "Drogo" }, { id: "2", type: "cat", name: "Cindy" } ] }; function mkhtml(js){ return Object.values(js).map(v=> '<div>'+((typeof v)=='object' ?v.map(e=> '<p>'+Object.values(e).join('</p><p>')+'<p>').join('') :v)+'</div>').join(''); } console.log(mkhtml(json));

同樣,使用傳統的函數語法:

 const json = { name: "superman", place: "universe", pets: [ { id: "1", type: "dog", name: "Drogo" }, { id: "2", type: "cat", name: "Cindy" } ] }; function mkhtml(js){ return Object.values(js).map(function(v){ return '<div>'+((typeof v)=='object' ?v.map(function(e){return '<p>'+Object.values(e).join('</p><p>')+'<p>'}).join('') :v)+'</div>'; }).join(''); } console.log(mkhtml(json));

我剛剛將最后剩余的箭頭函數再次轉換為“舊”函數形式。

邏輯:

外部.map()適用於存儲在變量json中的對象的所有數組Object.values() :對於每個值v創建一個新的<div> ,然后用值v本身或一系列<p>元素,以防v結果是一個對象(實際上,它是一個對象數組!)在這種情況下, <p>用每個數組元素的對象的值填充。

如果您希望它更加模塊化,也許您可​​以將您的功能拆分為許多小功能助手:

 const json = {"name":"superman","place":"universe","pets":[{"id":"1","type":"dog","name":"Drogo"},{"id":"2","type":"cat","name":"Cindy"}]}; // Return a string given string and el args const toEl = (str, el) => `<${el}>${str}</${el}>`; // Call toEl with a string and 'div' param const toDiv = (str) => toEl(str, 'div'); // Call toEl with a string and 'p' param const toPara = (str) => toEl(str, 'p'); // Iterate over the array, and then // iterate over each object calling getPara // for each value function getArr(arr) { return arr.map(obj => { return Object.values(obj).map(v => { return toPara(v); }).join(''); }).join(''); } // Now just join it all together function getHTMLString(obj) { const name = toDiv(obj.name); const place = toDiv(obj.place); const pets = toDiv(getArr(obj.pets)); return `<body>${name}${place}${pets}</body>`; } console.log(getHTMLString(json));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM