简体   繁体   English

将 JSON 对象转换为 html 字符串

[英]convert JSON object to html string

I have a JSON:我有一个 JSON:

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

The requirement is to change this to a html string like so:要求是将其更改为 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> ' ' <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> '

I wrote the below function to solve it.我写了下面的函数来解决它。 Basically I am iterating through json using Object.entries to obtain [key, value] pair and then appending the value to myStr, my final string variable.基本上,我使用 Object.entries 遍历 json 以获得 [key, value] 对,然后将该值附加到 myStr,我的最终字符串变量。 But I cannot retain the strings thus formed.但我不能保留这样形成的字符串。

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 need some help with my logic.我的逻辑需要一些帮助。 Further, I have a few issues:此外,我有几个问题:

i) How do I write 1 function that contains all of these features, including myStr variable, such that my code is modular ii) Why isn't myStr able to remember previous string? i) 如何编写包含所有这些功能的 1 个函数,包括 myStr 变量,以便我的代码是模块化的 ii) 为什么 myStr 不能记住以前的字符串? iii) In such type of problems, is it wise to just go through the specific json object and iterate through it or there should be a more generic function that checks for object, string or Array within the json and then generates string accordingly? iii) 在此类问题中,仅通过特定的 json 对象并对其进行迭代是明智的,还是应该有一个更通用的函数来检查 json 中的对象、字符串或数组,然后相应地生成字符串?

You were not adding the items in the property which was an array of Objects, you can use Object.values() to iterate over the values and append to the <p> tag.您没有在作为对象数组的属性中添加项目,您可以使用Object.values()迭代这些值Object.values()加到<p>标签。

Also you did not re-assign the new string formed in the printString() function back to the myStr variable, so as a result the new string that was generated was lost.此外,您没有将printString()函数中形成的新字符串重新分配回myStr变量,因此生成的新字符串丢失了。

This is because string is immutable appending a new string to an older one will create a new instance of a string:这是因为 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);

It looks a bit ugly but still works, If you know how deep your array is then I wouldn't go with recursion.它看起来有点难看但仍然有效,如果你知道你的数组有多深,那么我不会使用递归。

Working proof: https://jsfiddle.net/bajuck9y/工作证明: https : //jsfiddle.net/bajuck9y/

JS 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>';

  }

}

Or, maybe, do it this way?或者,也许,这样做?

 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));

And the same again, with conventional function syntax:同样,使用传统的函数语法:

 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));

I just converted the last remaining arrow function to the "old" function form again.我刚刚将最后剩余的箭头函数再次转换为“旧”函数形式。

The logic:逻辑:

The outer .map() works on all the array Object.values() of the object that is stored in the variable json : for each value v a new <div> is created which is then filled with either the value v itself or a series of <p> elements in case v turns out to be an object (actually, it is an array of objects!) In this case the <p> s are filled with the values of each array element's object.外部.map()适用于存储在变量json中的对象的所有数组Object.values() :对于每个值v创建一个新的<div> ,然后用值v本身或一系列<p>元素,以防v结果是一个对象(实际上,它是一个对象数组!)在这种情况下, <p>用每个数组元素的对象的值填充。

If you want it to be more modular maybe you could split out your function into a number of small function helpers:如果您希望它更加模块化,也许您可​​以将您的功能拆分为许多小功能助手:

 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