SOAP response (XML) to JSON - javascript

I need to consume a SOAP web service which, naturally, sends its response in XML, since I'm developing a Appcelerator Titanium mobile app I would prefer the response in JSON. After looking online I converted the response using this Javascript code, it mostly worked but returned results such as the following:
{
"SOAP-ENV:Body" : {
"ns1:linkAppResponse" : {
"ns1:result" : {
#text : true;
};
"ns1:uuid" : {
#text : "a3dd915e-b4e4-43e0-a0e7-3c270e5e7aae";
};
};
};
}
Of course the colons and hashes in the caused problems so I adjusted the code to do a substring on the name and drop off anything before the ':', then a stringified the resulting JSON, removed all the hashes and parsed the JSON again. This is a bit messy for my liking but I end up with something usable.
Here is the xmlToJson code I'm using:
// Changes XML to JSON
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) {// element
// do attributes
if (xml.attributes.length > 0) {
obj["#attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["#attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) {// text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName.substring(item.nodeName.indexOf(":") + 1);
if ( typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if ( typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
module.exports = xmlToJson;
Which results in the following JSON:
{
Body : {
linkAppResponse : {
result : {
text : true;
};
uuid : {
text : "9022d249-ea8a-47a3-883c-0f4cfc9d6494";
};
};
};
}
While this returns a JSON object I can use, I would prefer to have the resulting JSON in the following form:
{
result : true;
uuid : "9022d249-ea8a-47a3-883c-0f4cfc9d6494";
};
Mostly so it's less verbose and I can simply call json.result in order check if the query was successful instead of json.Body.linkAppResponse.result.text
Any help is greatly appreciated.

Came up with a working solution, not any less dirty but it works and returns data in the format I want.
function soapResponseToJson(xml) {
var json = xmlToJson(xml).Body;
console.debug(json);
var response = {};
for (var outterKey in json) {
if (json.hasOwnProperty(outterKey)) {
temp = json[outterKey];
for (var innerKey in temp) {
if (temp.hasOwnProperty(innerKey)) {
response[innerKey] = temp[innerKey].text;
}
}
}
}
console.debug(response);
return response;
}
// Changes XML to JSON
function xmlToJson(xml) {
// Create the return object
var obj = {};
if (xml.nodeType == 1) {// element
// do attributes
if (xml.attributes.length > 0) {
obj["#attributes"] = {};
for (var j = 0; j < xml.attributes.length; j++) {
var attribute = xml.attributes.item(j);
obj["#attributes"][attribute.nodeName] = attribute.nodeValue;
}
}
} else if (xml.nodeType == 3) {// text
obj = xml.nodeValue;
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
var nodeName = item.nodeName.substring(item.nodeName.indexOf(":") + 1).replace('#', '');
if ( typeof (obj[nodeName]) == "undefined") {
obj[nodeName] = xmlToJson(item);
} else {
if ( typeof (obj[nodeName].push) == "undefined") {
var old = obj[nodeName];
obj[nodeName] = [];
obj[nodeName].push(old);
}
obj[nodeName].push(xmlToJson(item));
}
}
}
return obj;
};
module.exports = soapResponseToJson;
console.debug(json):
{
linkAppResponse : {
result : {
text : true;
};
uuid : {
text : "e4f78c5f-1bc2-4b50-a749-19d733b9be3f";
};
};
}
console.debug(response):
{
result : true;
uuid : "e4f78c5f-1bc2-4b50-a749-19d733b9be3f";
}
I'm going to leave this question open for a while in case someone comes up with a better solution.

I feel like this is a fairly ugly solution (hope it doesn't offend you :) ).
Why don't you marshal the xml to an object and then use gson or jackson to map to json.
I don't know what framework you use, in spring for example, you can use jaxb2 to marshal and jackson or gson to transform your object to json.

Related

Array Data to HTML Table

What is the best way to get data from an array using tabletop.js into an html table? I am trying to take the data from the array and replace the dummy data that I currently have in there. The link below better explains what I'm trying to do.
Example of Data & Table
Here is my Fiddle: https://jsfiddle.net/1qeydx4f/
HTML:
<script type="text/javascript">
var publicSpreadsheetUrl = 'https://docs.google.com/spreadsheets/d/16EypE4AkZVutLblpQEpsBu4ly7ziqBRYPxlv7wO1SJs/edit?usp=sharing';
function init() {
Tabletop.init( { key: publicSpreadsheetUrl,
callback: showInfo,
simpleSheet: true } )
}
function showInfo(data, tabletop) {
console.log(data);
}
window.addEventListener('DOMContentLoaded', init)
</script>
<div class="docs-section" id="tables">
<h6 class="docs-header">3-Pointers Made (2019)</h6>
<p> </p>
<div class="docs-example">
<table class="u-full-width">
<thead>
<tr>
<th>Name</th>
<th>Team</th>
<th>Made</th>
<th>Attempted</th>
<th>Percent</th>
</tr>
</thead>
<tbody>
<tr>
<td>Dave Gamache</td>
<td>GS</td>
<td>150</td>
<td>300</td>
<td>50%</td>
</tr>
<tr>
<td>Dwayne Johnson</td>
<td>DAL</td>
<td>128</td>
<td>298</td>
<td>43%</td>
</tr>
</tbody>
</table>
</div>
</div>
Tabletop.js:
(function() {
'use strict';
var inNodeJS = typeof process !== 'undefined' && !process.browser;
var request = function requestNotProvided() {
throw new Error("The 'request' module is only available while running in Node.");
};
if(inNodeJS) { // This will get stripped out by Uglify, and Webpack will not include it
request = require('request');
}
var supportsCORS = false;
var inLegacyIE = false;
try {
var testXHR = new XMLHttpRequest();
if (typeof testXHR.withCredentials !== 'undefined') {
supportsCORS = true;
} else {
if ('XDomainRequest' in window) {
supportsCORS = true;
inLegacyIE = true;
}
}
} catch (e) { }
// Create a simple indexOf function for support
// of older browsers. Uses native indexOf if
// available. Code similar to underscores.
// By making a separate function, instead of adding
// to the prototype, we will not break bad for loops
// in older browsers
var indexOfProto = Array.prototype.indexOf;
var ttIndexOf = function(array, item) {
var i = 0, l = array.length;
if (indexOfProto && array.indexOf === indexOfProto) {
return array.indexOf(item);
}
for (; i < l; i++) {
if (array[i] === item) {
return i;
}
}
return -1;
};
/*
Initialize with Tabletop.init( { key: '0AjAPaAU9MeLFdHUxTlJiVVRYNGRJQnRmSnQwTlpoUXc' } )
OR!
Initialize with Tabletop.init( { key: 'https://docs.google.com/spreadsheet/pub?hl=en_US&hl=en_US&key=0AjAPaAU9MeLFdHUxTlJiVVRYNGRJQnRmSnQwTlpoUXc&output=html&widget=true' } )
OR!
Initialize with Tabletop.init('0AjAPaAU9MeLFdHUxTlJiVVRYNGRJQnRmSnQwTlpoUXc')
*/
var Tabletop = function(options) {
// Make sure Tabletop is being used as a constructor no matter what.
if(!this || !(this instanceof Tabletop)) {
return new Tabletop(options);
}
if(typeof(options) === 'string') {
options = { key : options };
}
this.callback = options.callback;
this.wanted = options.wanted || [];
this.key = options.key;
this.simpleSheet = !!options.simpleSheet;
this.parseNumbers = !!options.parseNumbers;
this.wait = !!options.wait;
this.reverse = !!options.reverse;
this.postProcess = options.postProcess;
this.debug = !!options.debug;
this.query = options.query || '';
this.orderby = options.orderby;
this.endpoint = options.endpoint || 'https://spreadsheets.google.com';
this.singleton = !!options.singleton;
this.simpleUrl = !!(options.simpleUrl || options.simple_url); //jshint ignore:line
this.authkey = options.authkey;
this.sheetPrivacy = this.authkey ? 'private' : 'public'
this.callbackContext = options.callbackContext;
// Default to on, unless there's a proxy, in which case it's default off
this.prettyColumnNames = typeof(options.prettyColumnNames) === 'undefined' ? !options.proxy : options.prettyColumnNames;
if(typeof(options.proxy) !== 'undefined') {
// Remove trailing slash, it will break the app
this.endpoint = options.proxy.replace(/\/$/,'');
this.simpleUrl = true;
this.singleton = true;
// Let's only use CORS (straight JSON request) when
// fetching straight from Google
supportsCORS = false;
}
this.parameterize = options.parameterize || false;
if (this.singleton) {
if (typeof(Tabletop.singleton) !== 'undefined') {
this.log('WARNING! Tabletop singleton already defined');
}
Tabletop.singleton = this;
}
/* Be friendly about what you accept */
if (/key=/.test(this.key)) {
this.log('You passed an old Google Docs url as the key! Attempting to parse.');
this.key = this.key.match('key=(.*?)(&|#|$)')[1];
}
if (/pubhtml/.test(this.key)) {
this.log('You passed a new Google Spreadsheets url as the key! Attempting to parse.');
this.key = this.key.match('d\\/(.*?)\\/pubhtml')[1];
}
if(/spreadsheets\/d/.test(this.key)) {
this.log('You passed the most recent version of Google Spreadsheets url as the key! Attempting to parse.');
this.key = this.key.match('d\\/(.*?)\/')[1];
}
if (!this.key) {
this.log('You need to pass Tabletop a key!');
return;
}
this.log('Initializing with key ' + this.key);
this.models = {};
this.modelNames = [];
this.model_names = this.modelNames; //jshint ignore:line
this.baseJsonPath = '/feeds/worksheets/' + this.key + '/' + this.sheetPrivacy +'/basic?alt=';
if (inNodeJS || supportsCORS) {
this.baseJsonPath += 'json';
} else {
this.baseJsonPath += 'json-in-script';
}
if(!this.wait) {
this.fetch();
}
};
// A global storage for callbacks.
Tabletop.callbacks = {};
// Backwards compatibility.
Tabletop.init = function(options) {
return new Tabletop(options);
};
Tabletop.sheets = function() {
this.log('Times have changed! You\'ll want to use var tabletop = Tabletop.init(...); tabletop.sheets(...); instead of Tabletop.sheets(...)');
};
Tabletop.prototype = {
fetch: function(callback) {
if (typeof(callback) !== 'undefined') {
this.callback = callback;
}
this.requestData(this.baseJsonPath, this.loadSheets);
},
/*
This will call the environment appropriate request method.
In browser it will use JSON-P, in node it will use request()
*/
requestData: function(path, callback) {
this.log('Requesting', path);
if (inNodeJS) {
this.serverSideFetch(path, callback);
} else {
//CORS only works in IE8/9 across the same protocol
//You must have your server on HTTPS to talk to Google, or it'll fall back on injection
var protocol = this.endpoint.split('//').shift() || 'http';
if (supportsCORS && (!inLegacyIE || protocol === location.protocol)) {
this.xhrFetch(path, callback);
} else {
this.injectScript(path, callback);
}
}
},
/*
Use Cross-Origin XMLHttpRequest to get the data in browsers that support it.
*/
xhrFetch: function(path, callback) {
//support IE8's separate cross-domain object
var xhr = inLegacyIE ? new XDomainRequest() : new XMLHttpRequest();
xhr.open('GET', this.endpoint + path);
var self = this;
xhr.onload = function() {
var json;
try {
json = JSON.parse(xhr.responseText);
} catch (e) {
console.error(e);
}
callback.call(self, json);
};
xhr.send();
},
/*
Insert the URL into the page as a script tag. Once it's loaded the spreadsheet data
it triggers the callback. This helps you avoid cross-domain errors
http://code.google.com/apis/gdata/samples/spreadsheet_sample.html
Let's be plain-Jane and not use jQuery or anything.
*/
injectScript: function(path, callback) {
var script = document.createElement('script');
var callbackName;
if (this.singleton) {
if (callback === this.loadSheets) {
callbackName = 'Tabletop.singleton.loadSheets';
} else if (callback === this.loadSheet) {
callbackName = 'Tabletop.singleton.loadSheet';
}
} else {
var self = this;
callbackName = 'tt' + (+new Date()) + (Math.floor(Math.random()*100000));
// Create a temp callback which will get removed once it has executed,
// this allows multiple instances of Tabletop to coexist.
Tabletop.callbacks[ callbackName ] = function () {
var args = Array.prototype.slice.call( arguments, 0 );
callback.apply(self, args);
script.parentNode.removeChild(script);
delete Tabletop.callbacks[callbackName];
};
callbackName = 'Tabletop.callbacks.' + callbackName;
}
var url = path + '&callback=' + callbackName;
if (this.simpleUrl) {
// We've gone down a rabbit hole of passing injectScript the path, so let's
// just pull the sheet_id out of the path like the least efficient worker bees
if(path.indexOf('/list/') !== -1) {
script.src = this.endpoint + '/' + this.key + '-' + path.split('/')[4];
} else {
script.src = this.endpoint + '/' + this.key;
}
} else {
script.src = this.endpoint + url;
}
if (this.parameterize) {
script.src = this.parameterize + encodeURIComponent(script.src);
}
this.log('Injecting', script.src);
document.getElementsByTagName('script')[0].parentNode.appendChild(script);
},
/*
This will only run if tabletop is being run in node.js
*/
serverSideFetch: function(path, callback) {
var self = this;
this.log('Fetching', this.endpoint + path);
request({url: this.endpoint + path, json: true}, function(err, resp, body) {
if (err) {
return console.error(err);
}
callback.call(self, body);
});
},
/*
Is this a sheet you want to pull?
If { wanted: ["Sheet1"] } has been specified, only Sheet1 is imported
Pulls all sheets if none are specified
*/
isWanted: function(sheetName) {
if (this.wanted.length === 0) {
return true;
} else {
return (ttIndexOf(this.wanted, sheetName) !== -1);
}
},
/*
What gets send to the callback
if simpleSheet === true, then don't return an array of Tabletop.this.models,
only return the first one's elements
*/
data: function() {
// If the instance is being queried before the data's been fetched
// then return undefined.
if (this.modelNames.length === 0) {
return undefined;
}
if (this.simpleSheet) {
if (this.modelNames.length > 1 && this.debug) {
this.log('WARNING You have more than one sheet but are using simple sheet mode! Don\'t blame me when something goes wrong.');
}
return this.models[this.modelNames[0]].all();
} else {
return this.models;
}
},
/*
Add another sheet to the wanted list
*/
addWanted: function(sheet) {
if(ttIndexOf(this.wanted, sheet) === -1) {
this.wanted.push(sheet);
}
},
/*
Load all worksheets of the spreadsheet, turning each into a Tabletop Model.
Need to use injectScript because the worksheet view that you're working from
doesn't actually include the data. The list-based feed (/feeds/list/key..) does, though.
Calls back to loadSheet in order to get the real work done.
Used as a callback for the worksheet-based JSON
*/
loadSheets: function(data) {
var i, ilen;
var toLoad = [];
this.googleSheetName = data.feed.title.$t;
this.foundSheetNames = [];
for (i = 0, ilen = data.feed.entry.length; i < ilen ; i++) {
this.foundSheetNames.push(data.feed.entry[i].title.$t);
// Only pull in desired sheets to reduce loading
if (this.isWanted(data.feed.entry[i].content.$t)) {
var linkIdx = data.feed.entry[i].link.length-1;
var sheetId = data.feed.entry[i].link[linkIdx].href.split('/').pop();
var jsonPath = '/feeds/list/' + this.key + '/' + sheetId + '/' + this.sheetPrivacy + '/values?alt=';
if (inNodeJS || supportsCORS) {
jsonPath += 'json';
} else {
jsonPath += 'json-in-script';
}
if (this.query) {
// Query Language Reference (0.7)
jsonPath += '&tq=' + this.query;
}
if (this.orderby) {
jsonPath += '&orderby=column:' + this.orderby.toLowerCase();
}
if (this.reverse) {
jsonPath += '&reverse=true';
}
toLoad.push(jsonPath);
}
}
this.sheetsToLoad = toLoad.length;
for(i = 0, ilen = toLoad.length; i < ilen; i++) {
this.requestData(toLoad[i], this.loadSheet);
}
},
/*
Access layer for the this.models
.sheets() gets you all of the sheets
.sheets('Sheet1') gets you the sheet named Sheet1
*/
sheets: function(sheetName) {
if (typeof sheetName === 'undefined') {
return this.models;
} else {
if (typeof(this.models[sheetName]) === 'undefined') {
// alert( "Can't find " + sheetName );
return;
} else {
return this.models[sheetName];
}
}
},
sheetReady: function(model) {
this.models[model.name] = model;
if (ttIndexOf(this.modelNames, model.name) === -1) {
this.modelNames.push(model.name);
}
this.sheetsToLoad--;
if (this.sheetsToLoad === 0) {
this.doCallback();
}
},
/*
Parse a single list-based worksheet, turning it into a Tabletop Model
Used as a callback for the list-based JSON
*/
loadSheet: function(data) {
var that = this;
new Tabletop.Model({
data: data,
parseNumbers: this.parseNumbers,
postProcess: this.postProcess,
tabletop: this,
prettyColumnNames: this.prettyColumnNames,
onReady: function() {
that.sheetReady(this);
}
});
},
/*
Execute the callback upon loading! Rely on this.data() because you might
only request certain pieces of data (i.e. simpleSheet mode)
Tests this.sheetsToLoad just in case a race condition happens to show up
*/
doCallback: function() {
if(this.sheetsToLoad === 0) {
this.callback.apply(this.callbackContext || this, [this.data(), this]);
}
},
log: function() {
if(this.debug) {
if(typeof console !== 'undefined' && typeof console.log !== 'undefined') {
Function.prototype.apply.apply(console.log, [console, arguments]);
}
}
}
};
/*
Tabletop.Model stores the attribute names and parses the worksheet data
to turn it into something worthwhile
Options should be in the format { data: XXX }, with XXX being the list-based worksheet
*/
Tabletop.Model = function(options) {
var i, j, ilen, jlen;
this.columnNames = [];
this.column_names = this.columnNames; // jshint ignore:line
this.name = options.data.feed.title.$t;
this.tabletop = options.tabletop;
this.elements = [];
this.onReady = options.onReady;
this.raw = options.data; // A copy of the sheet's raw data, for accessing minutiae
if (typeof(options.data.feed.entry) === 'undefined') {
options.tabletop.log('Missing data for ' + this.name + ', make sure you didn\'t forget column headers');
this.originalColumns = [];
this.elements = [];
this.ready();
return;
}
for (var key in options.data.feed.entry[0]){
if (/^gsx/.test(key)) {
this.columnNames.push(key.replace('gsx$',''));
}
}
this.originalColumns = this.columnNames;
this.original_columns = this.originalColumns; // jshint ignore:line
for (i = 0, ilen = options.data.feed.entry.length ; i < ilen; i++) {
var source = options.data.feed.entry[i];
var element = {};
for (j = 0, jlen = this.columnNames.length; j < jlen ; j++) {
var cell = source['gsx$' + this.columnNames[j]];
if (typeof(cell) !== 'undefined') {
if (options.parseNumbers && cell.$t !== '' && !isNaN(cell.$t)) {
element[this.columnNames[j]] = +cell.$t;
} else {
element[this.columnNames[j]] = cell.$t;
}
} else {
element[this.columnNames[j]] = '';
}
}
if (element.rowNumber === undefined) {
element.rowNumber = i + 1;
}
this.elements.push(element);
}
if (options.prettyColumnNames) {
this.fetchPrettyColumns();
} else {
this.ready();
}
};
Tabletop.Model.prototype = {
/*
Returns all of the elements (rows) of the worksheet as objects
*/
all: function() {
return this.elements;
},
fetchPrettyColumns: function() {
if (!this.raw.feed.link[3]) {
return this.ready();
}
var cellurl = this.raw.feed.link[3].href.replace('/feeds/list/', '/feeds/cells/').replace('https://spreadsheets.google.com', '');
var that = this;
this.tabletop.requestData(cellurl, function(data) {
that.loadPrettyColumns(data);
});
},
beforeReady: function() {
if(this.postProcess) {
for (i = 0, ilen = this.elements.length; i < ilen; i++) {
this.postProcess(element);
}
}
},
ready: function() {
this.beforeReady();
this.onReady.call(this);
},
/*
* Store column names as an object
* with keys of Google-formatted "columnName"
* and values of human-readable "Column name"
*/
loadPrettyColumns: function(data) {
var prettyColumns = {};
var columnNames = this.columnNames;
var i = 0;
var l = columnNames.length;
for (; i < l; i++) {
if (typeof data.feed.entry[i].content.$t !== 'undefined') {
prettyColumns[columnNames[i]] = data.feed.entry[i].content.$t;
} else {
prettyColumns[columnNames[i]] = columnNames[i];
}
}
this.prettyColumns = prettyColumns;
this.pretty_columns = this.prettyColumns; // jshint ignore:line
this.prettifyElements();
this.ready();
},
/*
* Go through each row, substitutiting
* Google-formatted "columnName"
* with human-readable "Column name"
*/
prettifyElements: function() {
var prettyElements = [],
orderedPrettyNames = [],
i, j, ilen, jlen;
for (j = 0, jlen = this.columnNames.length; j < jlen ; j++) {
orderedPrettyNames.push(this.prettyColumns[this.columnNames[j]]);
}
for (i = 0, ilen = this.elements.length; i < ilen; i++) {
var newElement = {};
for (j = 0, jlen = this.columnNames.length; j < jlen ; j++) {
var newColumnName = this.prettyColumns[this.columnNames[j]];
newElement[newColumnName] = this.elements[i][this.columnNames[j]];
}
prettyElements.push(newElement);
}
this.elements = prettyElements;
this.columnNames = orderedPrettyNames;
},
/*
Return the elements as an array of arrays, instead of an array of objects
*/
toArray: function() {
var array = [],
i, j, ilen, jlen;
for (i = 0, ilen = this.elements.length; i < ilen; i++) {
var row = [];
for (j = 0, jlen = this.columnNames.length; j < jlen ; j++) {
row.push(this.elements[i][ this.columnNames[j]]);
}
array.push(row);
}
return array;
}
};
if(typeof module !== 'undefined' && module.exports) { //don't just use inNodeJS, we may be in Browserify
module.exports = Tabletop;
} else if (typeof define === 'function' && define.amd) {
define(function () {
return Tabletop;
});
} else {
window.Tabletop = Tabletop;
}
})();
This can actually be achieved pretty simply. All you need to do is give your table an ID to be able to select it, and have a loop in the tabletop callback:
function gotData(data) {
const table = document.getElementById("table1-id").tBodies[0];
for (const player of data) {
const row = table.insertRow(-1); // index -1 inserts at bottom
const keys = Object.keys(player);
for (let i = 0; i < keys.length; i++) {
const c = row.insertCell(i);
c.appendChild(document.createTextNode(player[keys[i]]));
}
}
}

XML To JSON Conversion with attributes

I am trying to convert the XML to JSON.Here am facing challenge my xml have #attributes name as "value" in all tag. while convert into xml to JSON i am using the below code.
var xml = "<Message><id value="123"></id><type value="Test"></type></Message>"
var json = XMLtoJSON(xml, ["type", "space", "xmlns", "html"]);
var result = JSON.stringify(json)
function XMLtoJSON(xml, ignored) {
var r, children = xml.*, attributes = xml.#*, length = children.length();
if(length == 0) {
r = xml.toString();
} else if(length == 1) {
var text = xml.text().toString();
if(text) {
r = text;
}
}
if(r == undefined) {
r = {};
for each (var child in children) {
var name = child.localName();
var json = XMLtoJSON(child, ignored);
var value = r[name];
if(value) {
if(value.length) {
value.push(json);
} else {
r[name] = [value, json]
}
} else {
r[name] = json;
}
}
}
if(attributes.length()) {
var a = {}, c = 0;
for each (var attribute in attributes) {
var name = attribute.localName();
if(ignored && ignored.indexOf(name) == -1) {
a["_" + name] = attribute.toString();
c ++;
}
}
if(c) {
if(r) a._ = r;
return a;
}
}
return r;
}
Input XML :
<Message><id value="123"></id><type value="Test"></type></Message>
Actual Output:
{"id":{"_value":"123"},"type":{"_value":"Test"}}
Expected Output:
{"id":"123","type":"Test"}
Guide me where am missing the part to get the expected output.
Regards,
nkn1189
do you think if you do this way will work for you?
put your actual output from that parser to this function:
function convertToExpectedOutput(obj){
var result = {}
for (var i in obj){
if (i == "_value")
return obj[i];
else
result[i] = convertToExpectedOutput(obj[i])
}
return result;
}
convertToExpectedOutput(actualOutput)
So, for your array, hange the convertToExpectedOutput to this way and it will give the expected result:
function convertToExpectedOutput(obj){
var result = {}
for (var i in obj){
if (i == "_value")
return obj[i];
else
if (Array.isArray(obj[i])){
result[i] = [];
arr = obj[i]
for (var j in arr)
result[i].push(convertToExpectedOutput(arr[j]))
}
else
result[i] = convertToExpectedOutput(obj[i])
}
return result;
}

How to get an object from an XML document?

When parsing documents using the excellent libxmljs library in Node.js, I stumbled across a case where a lot of nested elements were found, and the only thing I had to do was create a JS object from it.
Here is what the code looks like :
if (node.type() == 'element') {
switch(node.name()) {
case 'element1': {
myObject.element1 = {}
for (var i = 0; i < node.childNodes().length; i++) {
if(node.type() == 'element') {
switch(node.name()) {
case 'element2': {
myObject.element1.element2 = node.text()
...
}}}}}}}}
/* didn't count the number of closing brackets, but you get the idea ^_^ */
Is there a faster or built-in way to do such things, create an object from an XML string (or part of it) using libxmlJS ?
Note that, if it helps, the parsed XML must be validated against a XTD schema (which can really easily be done using this library)
Thanks
Here is some non-working code that can be found on this article :
function XML2jsobj(node) {
var data = {};
// append a value
function Add(name, value) {
if (data[name]) {
if (data[name].constructor != Array) {
data[name] = [data[name]];
}
data[name][data[name].length] = value;
}
else {
data[name] = value;
}
};
// element attributes
var c, cn;
for (c = 0; cn = node.attributes[c]; c++) {
Add(cn.name, cn.value);
}
// child elements
for (c = 0; cn = node.childNodes[c]; c++) {
if (cn.nodeType == 1) {
if (cn.childNodes.length == 1 && cn.firstChild.nodeType == 3) {
// text value
Add(cn.nodeName, cn.firstChild.nodeValue);
}
else {
// sub-object
Add(cn.nodeName, XML2jsobj(cn));
}
}
}
return data;
}
From that code, I could build something that seems to work with the latest libxmljs release, here it is :
function XML2jsobj(node) {
var data = {};
// append a value
function Add(name, value) {
if (data[name]) {
if (data[name].constructor != Array) {
data[name] = [data[name]];
}
data[name][data[name].length] = value;
}
else {
data[name] = value;
}
};
for (var c = 0; c < node.attrs().length; c++) {
var cn = node.attrs()[c];
Add(cn.name, cn.value);
}
// child elements
for (var c = 0; c < node.childNodes().length; c++) {
var cn = node.childNodes()[c];
if (cn.type() == 'element') {
if (cn.childNodes().length == 1 && cn.childNodes()[0].type() == 'text') {
// text value
Add(cn.name(), cn.childNodes()[0].text());
}
else {
// sub-object
Add(cn.name(), XML2jsobj(cn));
}
}
}
return data;
}
I hope this will have helped someone.

Can this function be re-written recursively or more cleanly?

This function match sets an attribute (collapsed) to true or false depending on
the value of a string :
function match(children) {
var data = $scope.treeData
for (var i = 0; i < data.length; i++) {
var s = data[i]
for (var i2 = 0; i2 < s.children.length; i2++) {
var s2 = s.children[i2]
for (var i3 = 0; i3 < s2.children.length; i3++) {
for (var i4 = 0; i4 < s2.children[i3].children.length; i4++) {
var text = "";
if ($scope.searchText == undefined) {
text = ""
} else {
text = $scope.searchText
}
if (s2.children[i3].children[i4].label
.toLowerCase() === text.toLowerCase()) {
s2.children[i3].collapsed = false
}
}
}
}
}
}
Excluding the bad use of variable names i3,i2 etc is there a cleaner method ?
As the inner most loop requires access to the outer loop can recursion still be used ?
Update :
Data structure :
[{"label":"test","collapsed":false,"children":[{"label":"test","collapsed":false,"children":[],"$$hashKey":"002"}],"$$hashKey":"001"}]
Update 2 :
Using a recursive function but the string 'test' is not being matched :
http://jsfiddle.net/U3pVM/19196/
fiddle src :
<div ng-app>
<h2>Todo</h2>
<div ng-controller="TodoCtrl">
</div>
</div>
function TodoCtrl($scope) {
var json = [{"label":"test","collapsed":false,"children":[{"label":"test","collapsed":false,"children":[],"$$hashKey":"002"}],"$$hashKey":"001"}]
var searchText = 'test'
function match(node, searchText){
angular.forEach(node.children, function(idx, child){
node.collapsed = child.label.toLowerCase === searchText.toLowerCase
console.log(node.collapsed)
if(child.children.length > 0){
match(child, searchText);
}
});
}
match(json, searchText);
}
Please try this :
function match2(obj) {
if (obj.children) {
for (var i = 0; i < obj.children.length; i++) {
match2(obj.children[i]);
}
}
else {
var text = $scope.searchText ? $scope.searchText : "";
if (obj.label
.toLowerCase() === text.toLowerCase()) {
obj.collapsed = false
}
}
Your JSFiddle is very nearly there. I made a couple of changes for this working JSFiddle.
First, you were passing an array into match and not an object. I changed your json variable to be json instead by removing the outer [], but you could also have fixed this by passing in json[0].
The other change was that you had the two parameters, child and idx, were the wrong way round.
function match(node, searchText){
angular.forEach(node.children, function(child, idx){
node.collapsed = child.label.toLowerCase === searchText.toLowerCase
console.log(node.collapsed)
if(child.children.length > 0){
match(child, searchText);
}
});
}
Here's another way of doing it, using some:
function match (node, searchText) {
node.collapsed = node.children.some(function(child) {
return child.label.toLowerCase === searchText.toLowerCase;
});
angular.forEach(node.children, function(child, idx){
match(child, searchText);
})
}
I think something like this may work for you. I don't know anything about angular there might be something there that would make it easier.
var searchText = ($scope.searchText == undefined) ? "": $scope.searchText;
match($scope.treeData, searchText);
function match(node, searchText){
$.each(node.children, function(idx, child){
node.collapsed = child.label.toLowerCase === searchText.toLowerCase
if(child.children.length > 0){
match(child, searchText);
}
});
}

how to reindex object start from 0

I have an object output from below code how to set the index start from 0 in js?
Object
3: Object
id: 34
type: 0
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[i] = {};
obj[i]['id'] = data_id;
obj[i]['type'] = data_type;
}
}
console.log(obj);
Needs more jQuery ?
var arr = $(".list").filter(function() {
return $(this).data('type') != 0;
}).map(function() {
return { id : $(this).data('id'), type : $(this).data('type') };
}).get();
FIDDLE
Actually if you want to start in 0, use another variable and not "i" (which I think is 3 when you use it as index).
var obj = {};
var edited = false;
var obj_idx = 0;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
obj[obj_idx] = {};
obj[obj_idx]['id'] = data_id;
obj[obj_idx]['type'] = data_type;
obj_idx += 1;
}
}
console.log(obj);
I think this time obj will be something like:
Object
0: Object
id: 34
type: 0
you could fake object as array by Array.prototype.push.call, in that way you could also gain the side effect: obj.length. it's kinda ninja and elegant :]
var obj = {};
var edited = false;
for (var i = 0; i < $(".list").length; i++) {
var data_id = parseInt($(".list").eq(i).attr('data-id'));
var data_type = parseInt($(".list").eq(i).attr('data-type'));
if ((data_type != 0)) {
edited = true;
} else {
edited = false;
}
if (edited == true) {
Array.prototype.push.call(obj, {id: data_id, type: data_type});
}
}
I am going to give a very simple and readable example. Say you've got an object with the following structure:
Object
0: Object
key: 'some-key'
value: 'some-value'
1: Object
...
Then you might want to delete an entry from it and reindex the whole thing, this is how I do it:
// obj is Object from above
const reIndexed = Object.entries(obj).map((element, index) => {
if (parseInt(element[0] != index) {
element[0] = index.toString();
}
return element;
});

Categories

Resources