javascript - 在 react-native 中将 HTML 转换为 JSON
问题描述
我想将从网络请求收到的 HTML 转换为 JSON,以便我可以轻松读取这些值。
如果有办法直接从 HTML 读取值,请在评论中告诉我
我找到了这个库:https
://github.com/andrejewski/himalaya
但是当我尝试在我的应用程序中运行示例时,我得到了错误Cannot read property prototype of undefined
所以我假设这个库在 react-native 中不起作用,因为它包含一个核心 Node JS 模块。
这是代码:
import {parse} from 'himalaya'
const html = this.state.html
const json = parse(html)
console.log('', json)
一些示例 html 可能是:
<div class='post post-featured'>
<p>Himalaya parsed me...</p>
<!-- ...and I liked it. -->
</div>
此 html 的预期输出为:
[{
type: 'element',
tagName: 'div',
attributes: [{
key: 'class',
value: 'post post-featured'
}],
children: [{
type: 'element',
tagName: 'p',
attributes: [],
children: [{
type: 'text',
content: 'Himalaya parsed me...'
}]
}, {
type: 'comment',
content: ' ...and I liked it. '
}]
}]
是否有另一种方法/库可以将 HTML 转换为 JSON 以响应本机?
解决方案
使用你在 React Native 中提到的包没有问题。鉴于您已遵循所有必需的步骤,一切都按预期工作:
安装himalaya
:
cd project_dir
npm install himalaya
import
在文件顶部添加所需的:
import {parse} from 'himalaya';
在解析 HTML 结果之前,在代码中的某处设置html
属性:state
this.setState = { html: '<div>Example HTML content</div>' };
使用对象将 HTML 转换为 JSON parse
:
const html = this.state.html;
const json = parse(html);
alert(JSON.stringify(json));
您可以在此 Snack中检查上面的代码是否按预期工作。
推荐阅读
- python - Python:日期之间的差异问题
- javascript - 如何通过获取用户输入来创建数组。例如范围从 a 到 b 具有恒定的差异
- java - Spring Data Elasticsearch - 找不到能够从类型 [java.lang.Long] 转换为类型 [java.time.Instant] 的转换器
- python - 使用 opencv 从视频中生成帧
- php - .user.ini 文件中设置的时区不适用
- html - css classname :not(:first-child) 选择器不排除其类名的第一个孩子
- c# - 在 WPF 中序列化和反序列化 UserControl 依赖属性
- azure - 如何在不停止 VM 的情况下更改 VM 公共 IP 地址
- reactjs - 更新使用 firebase 托管的 react 项目
- javascript - load 函数不加载新内容