简体   繁体   English

如何从类似 json 的字符串中渲染 html?

[英]How can I render an html from a json-like string?

This is part of the response from a server这是来自服务器的响应的一部分

{\"attributes\":{\"size\":\"18px\",\"color\":\"#3ba0dc\"},\"insert\":\"Vocabulary:\"}

the page I'm studying renders it like this我正在研究的页面呈现这样

在此处输入图像描述

What type of tag/language is that?那是什么类型的标签/语言?

How do I parse and render that source?如何解析和呈现该源?

You can use JSON.parse to parse your data and remove all the unwanted slashes.您可以使用JSON.parse来解析您的数据并删除所有不需要的斜杠。 Your response is in string format at current.您的回复目前是字符串格式。

Also you access the object you need to use .您还可以访问需要使用的 object . you get the value of that key.你得到那个键的值。 In your case its Vocabulary在你的情况下,它的Vocabulary

  1. To show the text Vocabulary We can use textContent()要显示文本Vocabulary我们可以使用textContent()
  2. To apply font size of your response to the word we can use element.style.fontSize要将您的响应的字体大小应用于单词,我们可以使用element.style.fontSize
  3. To apply color of your response to the word we can use element.style.color要将您的回复颜色应用于单词,我们可以使用element.style.color

Run snippet below.运行下面的代码段。

 //Your response in string format let response = '{\"attributes\":{\"size\":\"18px\",\"color\":\"#3ba0dc\"},\"insert\":\"Vocabulary:\"}' //Parse data let parsedData = JSON.parse(response) //Show text on div using querySelector let element = document.querySelector('#data') //Apply response data to your Vocabulary: element.textContent = parsedData.insert; element.style.fontSize = parsedData.attributes.size; element.style.color = parsedData.attributes.color; //Console log console.log(parsedData)
 <div id="data"></div>

This is stringify format of JSON data.这是JSON数据的字符串化格式。 so you need to parse it.所以你需要解析它。

 console.log( JSON.parse( '{\"attributes\":{\"size\":\"18px\",\"color\":\"#3ba0dc\"},\"insert\":\"Vocabulary:\"}' ) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM