Reputation: 664
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?
Upvotes: 4
Views: 5945
Reputation: 5090
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.
Upvotes: 3