将 HTML 有效负载解析为 JSON
Posted
技术标签:
【中文标题】将 HTML 有效负载解析为 JSON【英文标题】:Parse HTML payload to JSON 【发布时间】:2019-12-27 21:39:07 【问题描述】:我遇到了以下有效负载的问题。
我在 API 调用的 Node.js 后端收到的有效负载如下。
"id": "1",
"content":
"text": "
<body>
<div>
<table>
<thead>
<tr>
<th><strong>Header 1</strong></th>
<th><strong>Header 2</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>question 1</td>
<td>answer 1</td>
</tr>
<tr>
<td>question 2</td>
<td>answer 2</td>
</tr>
<tr>
<td>question 3</td>
<td>answer 3</td>
</tr>
</tbody>
</table>
</div>
</body>
"
所以在这里我将响应存储如下:
var response = data
即数据是 JSON 响应
我将 html 数据保存如下
var HTMLContentText = response.content.text
结果我会得到这个:
<body>
<div>
<table>
<thead>
<tr>
<th><strong>Header 1</strong></th>
<th><strong>Header 2</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>question 1</td>
<td>answer 1</td>
</tr>
<tr>
<td>question 2</td>
<td>answer 2</td>
</tr>
<tr>
<td>question 3</td>
<td>answer 3</td>
</tr>
</tbody>
</table>
</div>
</body>
这里我要执行以下操作
-
将 HTML 文本解析为对象
从响应中获取表格
即 select("table").first();
获取表格的行
即选择(“tr”)
我在 JAVA 中有相同的代码。
这里仅供参考。在这里,我使用 Jsoup 解析器来完成所有操作。我现在想用 javascript 执行所有操作。
// HTML as text (from JSON)
String HtmlFormattedText = (String)((JSONObject)JsonObject.get("content")).get("text");
// parse the html text into an object
Document HtmlFormattedDocumentObject = Jsoup.parse(HtmlFormattedText);
// get the table from the response
Element allRowsFromTable = HtmlFormattedDocumentObject.select("table").first();
// get the rows of the table
return allRowsFromTable.select("tr");
【问题讨论】:
我编辑了你的问题,所以它告诉其他人这不仅仅是关于 JavaScript,而是关于 Node.js。在你的情况下,这意味着很多。 (编辑等待同行评审,如果您看不到它。) 感谢您的编辑。我忘了提到关键的事情XD 【参考方案1】:我为此创建了一个 sn-p。函数的返回值包含表格的所有 tr 元素 - 您无需先选择表格。
const response =
"id": "1",
"content":
"text": `
<body>
<div>
<table>
<thead>
<tr>
<th><strong>Header 1</strong></th>
<th><strong>Header 2</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td>question 1</td>
<td>answer 1</td>
</tr>
<tr>
<td>question 2</td>
<td>answer 2</td>
</tr>
<tr>
<td>question 3</td>
<td>answer 3</td>
</tr>
</tbody>
</table>
</div>
</body>
`
// logging the result of the function
console.log(parseTable(response.content.text))
function parseTable(string)
// creating an HTML element
const el = document.createElement('html')
// adding the string to the HTML element
el.innerHTML = string
// selecting and returning all tr elements
return el.getElementsByTagName('tr')
注意:我将您数据中的单引号更改为反引号,因为它允许多行字符串。
【讨论】:
我收到此错误:document is not defined
可能是因为我在一个没有 HTML 正文或未附加到任何 HTML 文件的 JS 文件中编码
如果您在后端工作(例如使用 Node.js),那么就没有 document。是这样吗?
现在我看到了你的下一条评论——它是 Node.js。
那么这个答案可能对你有更多帮助:***.com/questions/21617468/node-js-generate-html
另一种解决方案是在字符串上使用正则表达式。以上是关于将 HTML 有效负载解析为 JSON的主要内容,如果未能解决你的问题,请参考以下文章
在 POST Spring 4.x MVC 上未解析 JSON 有效负载
为啥 NSJSONSerialization 将 NSDictionary 错误地解析为 JSON?