Html в json строку

Html в json строку

Parses HTML strings into objects using flexible, composable filters.

htmlToJson.parse(html, filter, [callback]) -> promise

The parse() method takes a string of HTML, and a filter, and responds with the filtered data. This supports both callbacks and promises.

var promise = htmlToJson.parse('
content
'
,
'text': function ($doc)
return $doc.find('div').text();
>
>, function (err, result)
console.log(result);
>);
promise.done(function (result)
//Works as well
>);

htmlToJson.request(requestOptions, filter, [callback]) -> promise

The request() method takes options for a call to the request library and a filter, then returns the filtered response body.

var promise = htmlToJson.request('http://prolificinteractive.com/team',
'images': ['img', function ($img)
return $img.attr('src');
>]
>, function (err, result)
console.log(result);
>);

htmlToJson.batch(html, dictionary, [callback]) -> promise

Performs many parsing operations against one HTML string. This transforms the HTML into a DOM only once instead of for each filter in the dictionary, which can quickly get expensive in terms of processing. This also allows you to break your filters up into more granular components and mix and match them as you please.

The values in the dictionary can be htmlToJson.Parser objects, generated methods from htmlToJson.createMethod , or naked filters that you might normally pass into htmlToJson.parse . For example:

return getProlificHomepage().then(function (html)
return htmlToJson.batch(html,
sections: htmlToJson.createParser(['#primary-nav a',
'name': function ($section)
return $section.text();
>,
'link': function ($section)
return $section.attr('href');
>
>]),
offices: htmlToJson.createMethod(['.office',
'location': function ($office)
return $office.find('.location').text();
>,
'phone': function ($office)
return $office.find('.phone').text();
>
>]),
socialInfo: ['#footer .social-link',
'name': function ($link)
return $link.text();
>,
'link': function ($link)
return $link.attr('href');
>
>]
>);
>);

htmlToJson.createMethod(filter) -> function (html, [callback])

Generates a method that wraps the passed filter argument. The generated method takes an HTML string and processes it against that filter .

var parseFoo = htmlToJson.createMethod(
'foo': function ($doc)
return $doc.find('#foo').bar();
>
>);

htmlToJson.createParser(filter), new htmlToJson.Parser(filter)

For the sake of reusability, creates an object with .parse and .request helper methods, which use the passed filter. For example:

var linkParser = htmlToJson.createParser(['a[href]',
'text': function ($a)
return $a.text();
>,
'href': function ($a)
return $a.attr('href');
>
>]);
linkParser.request('http://prolificinteractive.com').done(function (links)
//Do stuff with links
>);
linkParser.request('http://prolificinteractive.com', ['a[href]',
'text': function ($a)
return $a.text();
>,
'href': function ($a)
return $a.attr('href');
>
>]).done(function (links)
//Do stuff with links
>);

The former allows you to easily reuse the filter (and make it testable), while that latter is a one-off.

Parses the passed html argument against the parser’s filter.

Returns a method that wraps parser.parse()

Makes a request with the request options, then runs the response body through the parser’s filter.

The return values of functions are mapped against their corresponding keys. Function filters are passed cheerio objects, which allows you to play with a jQuery-like interface.

htmlToJson.parse('
foo
'
,
'foo1': function ($doc, $)
return $doc.find('#foo').text(); //foo
>
>, callback);

Arrays of data can be parsed out by either using the .map() method within a filter function or using the shorthand [selector, filter] syntax:

A filter is applied incrementally against each matched element, and the results are returned within an array.

var html = '
1
2
'
;
htmlToJson.parse(html, function ()
return this.map('.item', function ($item)
return $item.text();
>);
>).done(function (items)
// Items should be: ['1','2']
>, function (err)
// Handle error
>);

This is essentially a short-hand alias for .map() , making the filter look more like its output:

var html = '
1
2
'
;
htmlToJson
.parse(html, ['.item', function ($item)
return $item.text();
>])
.done(function (items)
// Items should be: ['1','2']
>, function (err)
// Handle error
>);

As an added convenience you can pass in a 3rd argument into the array filter, which allows you to manipulate the results. You can return a promise if you wish to do an asynchronous operation.

var html = '
1
2
'
;
htmlToJson
.parse(html, ['.item', function ($item)
return +$item.text();
>, function (items)
return _.map(items, function (item)
return item * 3;
>);
>])
.done(function (items)
// Items should be: [3,6]
>, function (err)
// Handle error
>);

Filter functions may also return promises, which get resolved asynchronously.

function getProductDetails (id, callback)
return htmlToJson.request(
uri: 'http://store.prolificinteractive.com/products/' + id
>,
'id': function ($doc)
return $doc.find('#product-details').attr('data-id');
>,
'colors': ['.color',
'id': function ($color)
return $color.attr('data-id');
>,
'hex': function ($color)
return $color.css('background-color');
>
>]
>, callback);
>
function getProducts (callback)
return htmlToJson.request(
uri: 'http://store.prolificinteractive.com'
>, ['.product',
'id': function ($product)
return $product.attr('data-id');
>,
'image': function ($product)
return $product.find('img').attr('src');
>,
'colors': function ($product)
// This is where we use a promise to get the colors asynchronously
return this
.get('id')
.then(function (id)
return getProductDetails(id).get('colors');
>);
>
>], callback);
>

Dependencies on other values

Filter functions may use the .get(propertyName) to use a value from another key in that filter. This returns a promise representing the value rather than the value itself.

function getProducts (callback)
return htmlToJson.request('http://store.prolificinteractive.com', ['.product',
'id': function ($product)
return $product.attr('data-id');
>,
'image': function ($product)
return $product.find('img').attr('src');
>,
'colors': function ($product)
// Resolve 'id' then get product details with it
return this
.get('id')
.then(function (id)
return getProductDetails(id).get('colors');
>);
>
>], callback);
>

Nested objects within a filter are run against the same HTML context as the parent filter.

var html = '
foobar
'
;
htmlToJson.parse(html,
'foo':
'bar': function ($doc)
return $doc.find('#bar').text();
>
>
>);

You may specify a more specific DOM context by setting the $container property on the object filter:

var html = '
foobar
'
;
htmlToJson.parse(html,
'foo':
$container: '#foo',
'bar': function ($foo)
return $foo.find('#bar').text();
>
>
>);

Strings, numbers, and null values are simply used as the filter’s value. This especially comes in handy for incrementally converting from mock data to parsed data.

htmlToJson.parse(' ',
x: 1,
y: 'string value',
z: null
>);

Tests are written in mocha and located in the test directory. Run them with:

This script also executes jshint against lib/ and test/ directories.

Please read the existing code in order to learn the conventions.

Источник

How to Convert HTML Form Data to a JSON String in JavaScript?

Using JavaScript, you can choose different ways to convert HTML form values to a JSON string depending on the following:

Form Without Elements That Allow Multiple Selections

If your HTML form does not have elements that allow multiple selections (such as , checkboxes that have the same name , etc.), then you can simply do the following:

  1. Use the FormData API to access form data;
  2. Store form data (as key/value pairs) in an object;
  3. Convert form data object to a JSON string using the JSON.stringify() method.

For example, suppose you have the following HTML form:

You can access the submitted data from this HTML form and convert it to a JSON string in the following way:

The Object.fromEntries() was introduced in ES10. Therefore, to support earlier versions of ES, you could simply loop over the form data instead, for example, by using the FormData.entries() method, like so:

Form With Elements That Allow Multiple Selections

If your HTML form does have elements that allow multiple selections (such as , checkboxes that have the same name , etc.), then you can do the following:

  1. Use the FormData API to access form data;
  2. Store form data (as key/value pairs) in an object — if an element has multiple values, store an array of all the values. Otherwise, store the single value;
  3. Convert form data object to a JSON string using the JSON.stringify() method.

For example, suppose you have the following HTML form that has a multi-select and checkboxes with the same name attribute:

 
Hotel Apartments

You can access the submitted data from this HTML form and convert it to a JSON string in the following way:

// ES10+ const form = document.getElementById('myForm'); function formDataToObject(formData) < const normalizeValues = (values) =>(values.length > 1) ? values : values[0]; const formElemKeys = Array.from(formData.keys()); return Object.fromEntries( formElemKeys.map(key => Html в json строку) ); > form.addEventListener('submit', function (event) < event.preventDefault(); // 1: get form data const formData = new FormData(form); // 2: store form data in object const jsonObject = formDataToObject(formData); // 3: convert form data object to a JSON string const jsonString = JSON.stringify(jsonObject); console.log(jsonString); // '' >);

The Object.fromEntries() was introduced in ES10. Therefore, to support earlier versions of ES, you could simply loop over the form data instead, for example, by using the FormData.entries() method, like so:

// ES5+ const form = document.getElementById('myForm'); function formDataToObject(formData) < const normalizeValues = (values) =>(values.length > 1) ? values : values[0]; const object = <>; for (const Html в json строку of formData.entries()) < objectHtml в json строку = normalizeValues(formData.getAll(key)); >return object; >; form.addEventListener('submit', function (event) < event.preventDefault(); // 1: get form data const formData = new FormData(form); // 2: store form data in object const jsonObject = formDataToObject(formData); // 3: convert form data object to a JSON string const jsonString = JSON.stringify(jsonObject); console.log(jsonString); // '' >);

In either of the examples, the formDataToObject() function processes each form element and returns either a single value or an array of values, depending on whether the element has multiple values or not. This value is then added to its corresponding form element key in the resulting object.

Hope you found this post useful. It was published 22 Feb, 2023 . Please show your love and support by sharing this post.

Источник

Convert HTML to JSON

Convert HTML to JSON

This article introduces how to convert HTML code to JSON.

Use JavaScript JSON.stringify() Method to Convert HTML to JSON

JSON is similar to the JavaScript object, and the difference is that the key is written as a string in JSON. JSON is not language-dependent and is used to exchange data between applications or computers.

The example of a JSON string is shown below.

We can convert the HTML document in such representation using the JSON.stringify() method. The method converts the JavaScript object into a JSON string.

For example, we will convert the following HTML document into JSON.

div id='para'>  p>  Paragraph 1  p>  p>  Paragraph 2  p>  div> 

We need to get the document to be converted to JSON. In HTML, the id of the container to be converted is para .

Use the document.getElementById() method to return the document with para id. The para variable stores the whole HTML document.

var para = document.getElementById('para'); 

Next, use the outerHTML property to return the serialized HTML content of the para variable. The html variable contains the whole document in a string format.

Then, store the html string as a JavaScript object. Name the key of the object as html .

Finally, convert the object using the JSON.stringify() method.

var json = JSON.stringify(obj); 

Complete Source Code — JavaScript + Node.js:

var para = document.getElementById('para'); var html = para.outerHTML; var obj = < html: html >; var json = JSON.stringify(obj); console.log(json) 
"\n Paragraph 1\n

\n

\n Paragraph 2\n

\n
'>"

This way, we can convert any selected HTML to JSON.

Subodh is a proactive software engineer, specialized in fintech industry and a writer who loves to express his software development learnings and set of skills through blogs and articles.

Related Article — HTML Convert

Источник

Читайте также:  Java all mime types
Оцените статью