Map HTML to Json

Map HTML to JSON

I just wrote this function that does what you want; try it out let me know if it doesn't work correctly for you:

// Test with an element.
var initElement = document.getElementsByTagName("html")[0];
var json = mapDOM(initElement, true);
console.log(json);

// Test with a string.
initElement = "<div><span>text</span>Text2</div>";
json = mapDOM(initElement, true);
console.log(json);

function mapDOM(element, json) {
var treeObject = {};

// If string convert to document Node
if (typeof element === "string") {
if (window.DOMParser) {
parser = new DOMParser();
docNode = parser.parseFromString(element,"text/xml");
} else { // Microsoft strikes again
docNode = new ActiveXObject("Microsoft.XMLDOM");
docNode.async = false;
docNode.loadXML(element);
}
element = docNode.firstChild;
}

//Recursively loop through DOM elements and assign properties to object
function treeHTML(element, object) {
object["type"] = element.nodeName;
var nodeList = element.childNodes;
if (nodeList != null) {
if (nodeList.length) {
object["content"] = [];
for (var i = 0; i < nodeList.length; i++) {
if (nodeList[i].nodeType == 3) {
object["content"].push(nodeList[i].nodeValue);
} else {
object["content"].push({});
treeHTML(nodeList[i], object["content"][object["content"].length -1]);
}
}
}
}
if (element.attributes != null) {
if (element.attributes.length) {
object["attributes"] = {};
for (var i = 0; i < element.attributes.length; i++) {
object["attributes"][element.attributes[i].nodeName] = element.attributes[i].nodeValue;
}
}
}
}
treeHTML(element, treeObject);

return (json) ? JSON.stringify(treeObject) : treeObject;
}

Working example: http://jsfiddle.net/JUSsf/ (Tested in Chrome, I can't guarantee full browser support - you will have to test this).

​It creates an object that contains the tree structure of the HTML page in the format you requested and then uses JSON.stringify() which is included in most modern browsers (IE8+, Firefox 3+ .etc); If you need to support older browsers you can include json2.js.

It can take either a DOM element or a string containing valid XHTML as an argument (I believe, I'm not sure whether the DOMParser() will choke in certain situations as it is set to "text/xml" or whether it just doesn't provide error handling. Unfortunately "text/html" has poor browser support).

You can easily change the range of this function by passing a different value as element. Whatever value you pass will be the root of your JSON map.

Map html element to json object

Recursive function that builds the json. To ensure no issues with the keys (that have a possibility to be duplicates) the following was added :n where n is the index of the element.

function htmlToObject(targetElement) {  return Array    .from(targetElement.children)    .reduce((acc, cur, i) => {      acc[`${cur.tagName}:${i}`.toLowerCase()] = htmlToObject(cur);      return acc;    }, {});}
const startElement = document.getElementsByClassName("myparent")[0];
const res = { [startElement.tagName.toLowerCase()]: htmlToObject(startElement)};
console.log(res);
<div class='myparent'>  <div>    <div class="pdp-product-price">      <span> 650 rupees</span>      <div class="origin-block">        <span> 1,500 rupees</span>        <span>-57%</span>      </div>    </div>  </div></div>

How to convert selected HTML to Json?

What you want to do is called serializing.

//  This gives you an HTMLElement object
var element = document.getElementById('TextBoxesGroup');
// This gives you a string representing that element and its content
var html = element.outerHTML;
// This gives you a JSON object that you can send with jQuery.ajax's `data`
// option, you can rename the property to whatever you want.
var data = { html: html };

// This gives you a string in JSON syntax of the object above that you can
// send with XMLHttpRequest.
var json = JSON.stringify(data);

Convert Map to JSON object in Javascript

You could loop over the map and over the keys and assign the value

function createPaths(aliases, propName, path) {    aliases.set(propName, path);}
var map = new Map(), object = {};
createPaths(map, 'paths.aliases.server.entry', 'src/test');createPaths(map, 'paths.aliases.dist.entry', 'dist/test');
map.forEach((value, key) => { var keys = key.split('.'), last = keys.pop(); keys.reduce((r, a) => r[a] = r[a] || {}, object)[last] = value;});
console.log(object);

Creating Html to Json using .map, Facing issues to format it in exact format

Try this:

var mergedSections = {};
var section = $(".section").map(function() {
var section_id = $(this).attr("id");

var data = $(this).find(':input').map(function() {
var obj = {};
obj['id'] = $(this).attr("id");
obj['value'] = $(this).val();
return obj;
}).get();

mergedSections[section_id] = data;
});
console.log(mergedSections);

however you may wrap it with [] to reach your result:

console.log([mergedSections]);

working demo: https://jsfiddle.net/310wLyz9/

Parse HTML into a specific JSON object

Here's a solution that just relies on jQuery's .nextUntil() function.

var sections = [];

var eTitles = $('article').find('h2');

$(eTitles).each(function(){
var section = {
"title": {
"text": $(this).text(),
"href": $(this).find('a').attr('href')
},
"subtitles": []
}

var eSubtitles = $(this).nextUntil('h2').filter('h3, h4, h5');

$(eSubtitles).each(function(){
var subtitle = {
"text": $(this).text(),
"href": $(this).find('a').attr('href')
}

section.subtitles.push(subtitle);
});

sections.push(section);
});

Map String json content to HTML

You can use dangerouslySetInnerHTML as below:

<p dangerouslySetInnerHTML={{__html: p.body}}></p>

Reading JSON data into a webpage/html form from Google Maps Distance API

It looks like you need to get and display this data on the client-side, so you should use JavaScript to call the client-side Distance Matrix service. Not the web service (which is called server-side). E.g.:

HTML

<button id="distance-btn" onClick="getDistance()">
Click here for distance
</button>
<div id="distance"></div>

JS

function getDistance() {
const origin = '53.487362,-2.227197';
const destination = '51.516595,-0.129279';

var distanceService = new google.maps.DistanceMatrixService();
distanceService.getDistanceMatrix({
origins: [origin],
destinations: [destination],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.IMPERIAL,
avoidHighways: false,
avoidTolls: false
}, function(response, status) {
if (status !== 'OK') {
alert('Error was: ' + status);
} else {
const distance = response.rows[0].elements[0].distance.text
document.getElementById('distance').innerText = distance;
}
});
}

Working jsfiddle.

Having said that, if you only want to compute the distance between 1 origin and 1 destination then you're better off using the Directions service instead. Check out this other fiddle.

Hope this helps!



Related Topics



Leave a reply



Submit