首页 > 解决方案 > 在 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 以响应本机?

标签: javascripthtmljsonreact-native

解决方案


使用你在 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中检查上面的代码是否按预期工作。


推荐阅读