Convert XML Data to Json Format AngularJS - javascript

I am trying to use Treeview directive from AngularJS. The stored procedure is returning xml.The tree view directive takes json format. The Controller will get the data from service.I am stuck trying to convert xml to json in service.
Following is the xml structure:
<Company Data="New Company">
<Manager Data="Working">
<Employee Data="ABC" />
<Employee Data="DEF" />
<Employee Data="GHI">
<SubEmployee Data="Approval">
<Stuff Data="Financial" />
<Stuff Data="Consol" />
</SubEmployee>
<SubEmployee Data="Rolled-Over">
<Stuff Data="Corporate" />
</SubEmployee>
</Employee>
</Manager>
</Company>
Below is the expected JSON :
[
{
label: "New Company",
id: "Company",
children: [
{
label: "Working",
id: "Manager",
children: [
{
label: "ABC",
id: "Employee",
children: [
]
},
{
label: "DEF",
id: "Employee",
children: [
]
},
{
label: "GHI",
id: "Employee",
children: [
{
label: "Approval",
id: "SubEmployee",
children: [
{
label: "Financial",
id: "Stuff",
children: [
]
},
{
label: "Consol",
id: "Stuff",
children: [
]
}
]
},
{
label: "RolledOver",
id: "SubEmployee",
children: [
{
label: "Corporate",
id: "Stuff",
children: [
]
}
]
}
]
}
]
}
]

You have two choices:
Return the data from the API in the JSON format you require
Convert the XML to JSON in your angular application using javascript.
I would recommend option 1 if that is possible. For option 2 take a look at this question which disucsses XML/JSON conversion in Javascript
"Convert XML to JSON (and back) using Javascript"
If you read the answers on the above link you will see why option 1 is preferable. Converting between these formats can be problematic.

If you have JQuery available in that page you can convert the XML into a DOM object by doing var data = jQuery(data);. Then, use jQuery selectors to extract the data you need out of it.
Some examples:
// Extract an attribute from a node:
$scope.event.isLive = jQuery(data).find('event').attr('state') === 'Live';
// Extract a node's value:
$scope.event.title = jQuery('title', data).text();

A little late but I am also having to look at this option since I will be working with a CMS that only parses into XML. Which at this stage of the game I have no clue why... but I digress.
Found this on D-Zone and it seems to have potential:
https://dzone.com/articles/convert-xml-to-json-in-angular-js
Basically, you make the request to get the XML, then convert it to JSON within another function. Granted you are still pulling XML data but you will be able to work with JSON which will save you a lot of time.
EX from Site (Requires 3rd party Plugin X2JS)
var app = angular.module('httpApp', []);
app.controller('httpController', function ($scope, $http) {
$http.get("Sitemap.xml",
{
transformResponse: function (cnv) {
var x2js = new X2JS();
var aftCnv = x2js.xml_str2json(cnv);
return aftCnv;
}
})
.success(function (response) {
console.log(response);
});
});
One more note, if you are using Angular like me then someone has already created a nice plugin service to use:
https://github.com/johngeorgewright/angular-xml

Related

JSTree not displaying in container

I am trying to incorporate a JSTree structure into my javascript project; however, the tree doesn't seem to be displaying/rendering in its parent container. Here is the code that I am using to display the tree:
let tree=this.tree_div.find('#treeDiv');
tree.jstree(
{
"json_data":
{
"data": [
{
"data": "First",
"children": [{"data": "First"},{"data":"Second"},{"data": "Third"}]
},
{
"data": "Second",
"children": [{"data":"First"},{"data":"Second"},{"data": "Third"}]
},
{
"data": "Third",
"children": []
}
],
},
"plugins": ["checkbox","themes", "html_data", "ui"]
}
).bind("select_node.jstree", function(e, data){});
console.log(tree[0]);
In this example, #treeDiv is the div that is contained by the parent container.
In the last line where the value of the tree is printed, the following line comes up in the console:
To my understanding, this implies that the tree is being successfully initialized and set up, but it still isn't displaying on the web page. Any input would be appreciated. Thanks.
The most plausible explanation here would be that you are initializing the tree using the older jsTree API, while using the newer jsTree library.
Old JSON API: https://old.jstree.com/documentation/json_data
New JSON API: https://www.jstree.com/docs/json/
The newer API has a different object structure for populating the tree. Some of the functions and events remain the same, however many other things including the configuration object has changed.
myTree.jstree({ 'core' : {
'data' : [
'Simple root node',
{
'text' : 'Root node 2',
'state' : {
'opened' : true,
'selected' : true
},
'children' : [
{ 'text' : 'Child 1' },
'Child 2'
]
}
]
} });

Angularjs JSON treeview, json format issue

I'm trying to implement a JSON treeview with this plugin
My issue is this line :
$scope.structure = { folders: [
{ name: 'Folder 1', files: [{ name: 'File 1.jpg' }, { name: 'File 2.png' }], folders: [
{ name: 'Subfolder 1', files: [{ name: 'Subfile 1' }] },
{ name: 'Subfolder 2' },
{ name: 'Subfolder 3' }
]},
{ name: 'Folder 2' }
]};
In my case, I'm reading a file that returns me a JSON format
[
{
"item": {
"title": "Kids"
},
"children": [
{
"item": {
"title": "HELLO"
},
"children": []
}
]
}
]
I thought using JSON.parse(myFileContent) should have been enough for having the same data structure as in the $scope.structure but the data isn't displaying, i'm not getting errors.
How can I parse my file content to make it work ?
First, the structure should be an object, since the directive differentiates "folders" from "files". So, considering you already define child elements inside a children property, you could wrap your array (assuming it's called content) into an object like so:
$scope.structure = {
"children": content
};
Then, you'll need to override the default values for the property names in which the directive will try to get the values.
$scope.structureOptions = {
foldersProperty: "children",
displayProperty: "item.title"
};
And last, you add the tree-view-options attribute to the HTML element.
<div tree-view="structure" tree-view-options="structureOptions"></div>

JSON database module for Ruby/Sinatra? A JS lowDB alternative for Ruby/Sinatra?

I have to deal with a huge json like this acting as live datasource, is loaded every 5 min from a url..
sports: [
{
id: 200,
title: "Horse Racing",
meetings: [ ],
is_virtual: false,
events: [...],
pos: 83
},
{
id: 600,
title: "Tennis",
meetings: [ ],
is_virtual: false,
events: [
{
id: 301804310,
is_virtual: false,
outcomes: [
{
id: 32779738900,
description: "Brown/Pliskova",
},
{
id: 32779738900,
description: "Brown/Pliskova",
}]
}]
}]
And need to write methods like
getAllSports() returning an array object with all sports
getSport(sport_id) returning the object with this sport id
getAllEvents(Sport) returning all events list object of this sprot
getEvent(Sport, event_id) returning events that matches with given event_id
getOutcomes(Event, outcomes) ... and so on
Is there is a library that parses the json and already have methods some methods to help me to do this kind of stuff? example: obj.find(sport_id)...
In JS you have LowDB https://github.com/typicode/lowdb for this, any similar in Ruby/Sinatra? Or any approach suggestion? Im not using Rails.
Thanks in advice
You could always use Ruby's built in JSON library. You would be able to do something like
json_string = '{"name": "my name", "age": 5}'
object = JSON.parse(json_string)
object["name"] => "my name"
You can then use regular ruby hash / array functions on the returned object. In your case, you could do something along the lines of
def getSport(json_object, id)
json_object["sports"].select { | h | h["id"] == id }.first
end
Which, assuming you have already parsed the JSON and passed the resulting value into that function, would return the sport that had the given ID.

Howto convert JSON to Array

This is my first question to StackOverflow. I think answer is not so complicate, but I am very new to Javascript.
I have a JQuery AJAX function that parses this JSON object:
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
and should obtain the same result as:
var sections = [{
key: 1,
label: "Tom Clancy"
}, {
key: 12,
label: "Steve Martin"
}
];
I'm able to iterate through JSON element, but i don't know how to go on.
Can you provide suggestions?
EDIT: i can't still get it work...this is my code:
var sections=[
{key:1, label:"Section A"},
{key:2, label:"Section B"},
{key:3, label:"Section C"},
{key:4, label:"Section D"}
];
$.ajax({
url: '/WebOffice/ListaUtenti',
type: "POST",
dataType: 'json',
success: function (data)
{
console.log( "success" );
sections = data.Users;
}});
scheduler.createTimelineView({
name: "matrix",
x_unit: "day",
x_date: "%d %M",
x_step: 1,
x_size: 15,
y_unit: sections,
y_property: "section_id"
});
The jquery ajax call doesn't assign the new value to sections (the call state is success, verified) and so scheduler still shows the original sections. Where i'm wrong?
thanks
I will explain you the process. Go to any online JSON formatter, may be this one and pretty print your JSON. It will appear as.
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
So Users is an array of objects. Users[0] is first object and Users[1] is second object.
So you can iterate the JSON easily and obtain the result you want.
Live demo : http://jsfiddle.net/sbymr/
See the console for the output.

null array problem in json

I have written a function which scans all the files/directory in a given directory and returns a json object. I need to display this json object on the UI using jstree. I have written the function in go using recursion to scan all the files and directories rooted at that particular folder.
This is the type I am using to construct the whole structure
type Directory struct {
Name string "data"
SubDirs []Directory "children"
}
Now jstree accepts data structs of the following format.
json_data: {
data: [
"f1",
"f2",
{
data: "f3",
children: ["f4", "f5"]
}
]
}
and not of the format :-
json_data: {
data: [
{
"data": "f1",
"children": []
}
{
"data": "f2",
"children": []
}
{
data: "f3",
children: ["f4", "f5"]
}
]
}
(when I pass the above data structure format, it doesn't work probably since the "children" thing is null)
Thus the data structure Directory I have maintained doesn't suffice to construct the directory structure.
How do I solve this problem of constructing the Directory tree homogeneously?
The final one is not even valid JSON. The spec defines that empty arrays are valid and allowed. Try:
{
"data": [
{
"data": "f1",
"children": []
},
{
"data": "f2",
"children": []
},
{
"data": "f3",
"children": [
"f4",
"f5"
]
}
]
}
Use JSONLint to validate your JSON objects.

Categories

Resources