简体   繁体   中英

Convert HTML to JSON in react-native

I want to convert the HTML I received from a network request to JSON so I can easily read the values.
If there is a way to read values straight from HTML please let me know in a comment
I have found this library: https://github.com/andrejewski/himalaya
but when I try to run the example in my app I get the error Cannot read property prototype of undefined so I assume this library doesn't work in react-native because it contains a core Node JS module.
This was the code:

import {parse} from 'himalaya'
const html = this.state.html
const json = parse(html)
console.log('👉', json)

Some example html could be:

<div class='post post-featured'>
  <p>Himalaya parsed me...</p>
  <!-- ...and I liked it. -->
</div>

The expected output of this html is:

[{
  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. '
  }]
}]

Is there another way/library to convert HTML to JSON in react native?

There is no issue in using the package you have mentioned in React Native. Everything works as expected given you have followed all required steps:

Install himalaya :

cd project_dir
npm install himalaya

Add the required import at the top of your file:

import {parse} from 'himalaya';

Set the html property in state somewhere in your code, before parsing the HTML result:

this.setState = { html: '<div>Example HTML content</div>' };

Convert the HTML into JSON with parse object:

const html = this.state.html;
const json = parse(html);
alert(JSON.stringify(json));

You can check the code above works as expected in this Snack .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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