How to convert an array of JSON objects to valid XML? - javascript

Let's say I got an array of JSON objects like this:
const cars = [
{
"color": "purple",
"type": "minivan",
"registration": "2020-02-03",
"capacity": 7
},
{
"color": "orange",
"type": "SUV",
"registration": "2021-05-17",
"capacity": 4
},
{
"color": "green",
"type": "coupe",
"registration": "2019-11-13",
"capacity": 2
}
];
I want to convert this object to a valid XML. But the helper packages I use start tags as array indexes when converting it, and therefore the resulting XML is not valid.
For example: (function json2xml from goessner)
function json2xml(o, tab) {
var toXml = function(v, name, ind) {
var xml = "";
if (v instanceof Array) {
for (var i=0, n=v.length; i<n; i++)
xml += ind + toXml(v[i], name, ind+"\t") + "\n";
}
else if (typeof(v) == "object") {
var hasChild = false;
xml += ind + "<" + name;
for (var m in v) {
if (m.charAt(0) == "#")
xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
else
hasChild = true;
}
xml += hasChild ? ">" : "/>";
if (hasChild) {
for (var m in v) {
if (m == "#text")
xml += v[m];
else if (m == "#cdata")
xml += "<![CDATA[" + v[m] + "]]>";
else if (m.charAt(0) != "#")
xml += toXml(v[m], m, ind+"\t");
}
xml += (xml.charAt(xml.length-1)=="\n"?ind:"") + "</" + name + ">";
}
}
else {
xml += ind + "<" + name + ">" + v.toString() + "</" + name + ">";
}
return xml;
}, xml="";
for (var m in o)
xml += toXml(o[m], m, "");
return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
}
const cars = [
{
"color": "purple",
"type": "minivan",
"registration": "2020-02-03",
"capacity": 7
},
{
"color": "orange",
"type": "SUV",
"registration": "2021-05-17",
"capacity": 4
},
{
"color": "green",
"type": "coupe",
"registration": "2019-11-13",
"capacity": 2
}
];
console.log(json2xml(cars, ' '));
I tried xml2js, fast-xml-parser and jstoxml packages. Result is the same.
Edit:
Expected XML:
<element>
<color>purple</color>
<type>minivan</type>
<registration>2020-02-03</registration>
<capacity>7</capacity>
</element>
<element>
<color>orange</color>
<type>SUV</type>
<registration>2021-05-17</registration>
<capacity>4</capacity>
</element>
<element>
<color>green</color>
<type>coupe</type>
<registration>2019-11-13</registration>
<capacity>2</capacity>
</element>

How about this?
This assumes that the array of JSON objects all have the same keys.
let xml = "";
const prefixXML = `<?xml version="1.0" encoding="UTF-8"?>\n<cars>\n`;
const suffixXML = "\n</cars>";
const keys = Object.keys(cars[0]);
cars.forEach((car) => {
let valueXML = keys
.map((key) => {
return `<${key}>${car[key]}</${key}>`;
})
.join("\n\t");
xml += `
<car>
${valueXML}
</car>
`;
});
const final = prefixXML + xml + suffixXML;
console.log(final);
The XML output is:
<?xml version="1.0" encoding="UTF-8"?>
<cars>
<car>
<color>purple</color>
<type>minivan</type>
<registration>2020-02-03</registration>
<capacity>7</capacity>
</car>
<car>
<color>orange</color>
<type>SUV</type>
<registration>2021-05-17</registration>
<capacity>4</capacity>
</car>
<car>
<color>green</color>
<type>coupe</type>
<registration>2019-11-13</registration>
<capacity>2</capacity>
</car>
</cars>

If you're using FXP (fast-xml-parser), you can use folloing configuration to avoid array index as tag name
const parser = new j2xParser({
rootNodeName: "car"
});
const result = parser.parse(cars);
FXP version must be > 3.21.0

I'm the creator of jstoxml. Just for reference, this is how you'd structure your object to pass into jstoxml:
const { toXML } = window.jstoxml;
const cars = [
{
_name: 'element',
_content: {
color: 'purple',
type: 'minivan',
registration: '2020-02-03',
capacity: 7
}
},
{
_name: 'element',
_content: {
color: 'orange',
type: 'SUV',
registration: '2021-05-17',
capacity: 4
}
},
{
_name: 'element',
_content: {
color: 'green',
type: 'coupe',
registration: '2019-11-13',
capacity: 2
}
}
];
console.log(toXML(cars, { indent: ' ' }));
/**
Output:
<element>
<color>purple</color>
<type>minivan</type>
<registration>2020-02-03</registration>
<capacity>7</capacity>
</element>
<element>
<color>orange</color>
<type>SUV</type>
<registration>2021-05-17</registration>
<capacity>4</capacity>
</element>
<element>
<color>green</color>
<type>coupe</type>
<registration>2019-11-13</registration>
<capacity>2</capacity>
</element>
*/
<script src="https://cdn.jsdelivr.net/npm/jstoxml#2.2.4/dist/jstoxml.min.js"></script>

Related

Nested loop not getting expected result

Am having the arrays,
Now i need to get all tab names looping through and exclude the values present in exclude.
json1 ={
"sku Brand": "abc",
"strngth": "ALL",
"area": "",
"Country": "",
"local Brand": "",
"theme": "HideDisNameFilters"
}
json2 = {
"nav": [{
"tabname": "tab1",
"exclude':["area',"xyz"]
},
{
"tabname": "tab2",
"exclude":["Country"]
}
]}
var obj1 = json2.nav;
console.log(obj1)
Object.keys(obj1).forEach(function(prop) {
var str1 = "";
var maxLength = Object.keys(json1).length-2
Object.keys(json1).forEach(key => {
var str = "";
var t1 = "";
var index = Object.keys(json1).indexOf(key);
if(key != "theme"){
if(!obj1[prop]['exclude'].includes(key)){
str = key + "="+ json1[key];
str1 +=str&
console.log("str",str, " = ",str1 )
if(maxLength == index){
var t1 = "<a href="+str1 + "target='_blank'>"+ obj1[prop]['tabname'] +"</a>"
final_array.push(t1)
}
}
}
});
});
o/p should be: (it will exclude and form the url by checking from exclude array as below)
["<a href='sku+Brand=abc&Strngth=ALL&Country=&local+Brand=&' "target='_blank'>tab1<a>,"<a href='sku+Brand=abc&Strngth=ALL&area=&local+Brand=&' "target='_blank'>tab2<a>"]
AM not getting the correct output as expected...
Your code has several syntax errors (unbalanced quotes, mismatching quotes, trailing & without quotes, ...), and variables that have not been defined with var, let or const. It assigns to key_for_url, but never uses that value. It references a "slug" property, but that doesn't exist in your input data. It assumes a certain key order in plain objects, as it uses indexOf on Object.keys. This is a code smell. Variable names json1 and json2 are not very descriptive.
Here is code you could use:
let filter = {
"sku Brand": "abc",
"strngth": "ALL",
"area": "",
"Country": "",
"local Brand": "",
"theme": "HideDisNameFilters"
}
let tabs = {
"nav": [{
"tabname": "tab1",
"exclude": ["area", "xyz"]
},
{
"tabname": "tab2",
"exclude": ["Country"]
}
]
}
let result = tabs.nav.map(({tabname, exclude}) =>
`<a href='${
Object.entries(filter)
.filter(([key]) => !exclude.includes(key) && key != "theme")
.map(([key, value]) => `${key}=${value}`)
.join("&")
}' target='_blank'>${tabname}</a>`
);
console.log(result);
Solution:
obj1 is an array, so the loop will be obj1.forEach and accessing the value will be prop['exclude'].
I have made the code a bit more short.
json1 = {
"sku Brand": "abc",
"strngth": "ALL",
"area": "",
"Country": "",
"local Brand": "",
"theme": "HideDisNameFilters"
}
json2 = {
"nav": [{
"tabname": "tab1",
"exclude": ["area", "xyz"]
},
{
"tabname": "tab2",
"exclude": ["Country"]
}
]
}
final_array = []
var obj1 = json2.nav;
obj1.forEach(function (prop) {
let str = "";
Object.keys(json1).forEach((key) => {
if (!prop['exclude'].includes(key) && key !== 'theme') {
newKey = key.split(' ').join('+');
str = str + newKey + '=' + json1[key] + "&";
}
})
var t1 = "<a href=" + "'" + str + "'" + " target = '_blank' > "+ prop['tabname'] +" < /a>"
final_array.push(t1)
});
console.log(final_array)

How to generate minimum-size Javascript object?

How can I create a minimum-sized Javascript serialization of a Javascript object? Essentially a JSON.stringify with all unnecessary quotes removed. (Only basic JSON data types need to be supported, not Dates etc.)
For example, the JSON:
{
"pi": 3.14,
"e!": 4.26
}
would become:
{pi:3.14,"e!":4.26}
Edit: The result is not valid JSON, but is valid Javascript.
Copied from https://stackoverflow.com/a/11233515/916000 and modified:
function stringify(obj_from_json) {
if (typeof obj_from_json !== "object") {
return JSON.stringify(obj_from_json);
} else {
if (Array.isArray(obj_from_json)) {
// if the array contains an object
var arr = [];
for (var i = 0, len = obj_from_json.length; i < len; i++) {
arr.push(stringify(obj_from_json[i]));
}
return "[" + arr.join(",") + "]";
} else {
var props = Object
.keys(obj_from_json)
.map(function(key) {
return (new RegExp(/^[1-9a-zA-Z_$][a-zA-Z0-9_$.]*$/).test(key) ? key : "\"" + key + "\"") + ":" + stringify(obj_from_json[key]);
}).join(",");
return "{" + props + "}";
}
}
}
console.log(stringify({
"pi": 3.14,
"e!": 4.26
}));
console.log(stringify([{
"adjacencies": [{
"nodeTo": "graphnode2",
"nodeFrom": "graphnode1",
"data": {
"$color": "#557EAA"
}
}],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode1",
"name": "graphnode1"
}, {
"adjacencies": [],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode2",
"name": "graphnode2"
}]));
console.log(stringify({1: 2}));
console.log(stringify({"000": 42}));
console.log(stringify({1.26: 42}));
Edit: Added object array support.
Edit: Fixed array conversion.

How to stringify an Object which includes objects of array?

How to manipulate this object to URL query parameter.The example the the query parameter should be
advocates=7195&categories=25&checkbox-active=true&checkbox-close=undefined&checkbox-filed=true&checkbox-notFiled=undefined&cities=Delhi&cities=mumbai
Here is the code to convert any json no matter how deep it is into query params:
var o = {
"stage": 50,
"categories": [25, 23, 28],
"advocates": [{
"key": "7195",
"label": "kallol saikia"
}],
"cities": [{
"key": 390,
"label": "Delhi"
}, {
"key": 6,
"label": "Mumbai"
}],
"checkbox-filed": true,
"checkbox-active": true
}
function getParams(key, value) {
var queries = [];
var newKey;
if (Array.isArray(value)) {
for (var i = 0; i < value.length; i++) {
newKey = key + "[" + i + "]";
queries = queries.concat(getParams(newKey, value[i]));
}
} else if (value && typeof value === 'object' && value.constructor === Object) {
for (var prop in value) {
if (value.hasOwnProperty(prop)) {
newKey = key ? key + "[" + prop + "]" : prop;
queries = queries.concat(getParams(newKey, value[prop]));
}
}
} else {
queries.push(key + "=" + value);
}
return queries;
}
var query = getParams("", o).join("&");
console.log(query);
I hope this solves your issue.
Maybe:
var o = {
'advocates': [{
key: 1
}],
'checkbox-active': true
};
var query = Object.keys(o).map(function(i) {
var val;
if (Array.isArray(o[i])) {
val = o[i][0].key;
} else {
val = o[i];
}
return i + '=' + val;
}).join('&');
console.log(query);
You can try using Post Request
Send a JSON String using JSON.Parse() and JSON.stringify()
Convert your params array to JSON String and send that as a single query param.
Decode the query string param (i.e JSON string)
Adding Example
var jsonString = JSON.stringify({
"stage": 50,
"categories": [25, 23, 28],
"advocates": [{
"key": "7195",
"label": "kallol saikia"
}],
"cities": [{
"key": 390,
"label": "Delhi"
}, {
"key": 6,
"label": "Mumbai"
}],
"checkbox-filed": true,
"checkbox-active": true
});
// Pass down the Encoded Json
var encodedJson = encodeURI(jsonString);
console.log(encodedJson);
// Decode Json
var decodedJson = decodeURI(encodedJson);
var decodedObject = JSON.parse(decodedJson);
console.log(decodedObject);
Output
"%7B%22stage%22:50,%22categories%22:%5B25,23,28%5D,%22advocates%22:%5B%7B%22key%22:%227195%22,%22label%22:%22kallol%20saikia%22%7D%5D,%22cities%22:%5B%7B%22key%22:390,%22label%22:%22Delhi%22%7D,%7B%22key%22:6,%22label%22:%22Mumbai%22%7D%5D,%22checkbox-filed%22:true,%22checkbox-active%22:true%7D"
Object { stage: 50, categories: Array [25, 23, 28], advocates: Array [Object { key: "7195", label: "kallol saikia" }], cities: Array [Object { key: 390, label: "Delhi" }, Object { key: 6, label: "Mumbai" }], checkbox-filed: true, checkbox-active: true }
This algorithm will work. Just with caution, if you change the object structure, this might break
Hope this helps :>
var obj = {
"stage": 50,
"categories": [25, 23, 28],
"advocates": [{
"key": "7195",
"label": "kallol saikia"
}],
"cities": [{
"key": 390,
"label": "Delhi"
}, {
"key": 6,
"label": "Mumbai"
}],
"checkbox-filed": true,
"checkbox-active": true
}
let str = 'advocates=' + obj.advocates[0].key +
'&categories=' + obj.categories[0] +
'checkbox-active=' + obj['checkbox-active'] +
'checkbox-close=' + obj['checkbox-close'] +
'checkbox-filed=' + obj['checkbox-filed'] +
'checkbox-notFiled=' + obj['checkbox-notFiled'];
obj.cities.forEach(city=>str+= 'cities=' + city.label + '&')
str = str.substring(0,str.length-1)
console.log(str)
advocates=7195&
categories=25&
checkbox-active=true&
checkbox-close=undefined&
checkbox-filed=true&
checkbox-notFiled=undefined&
cities=Delhi&
cities=mumbai
`${key}${i>0?'&':''}${val[0]}=${val[1]}`, ""
'advocates':
'checkbox-active':
'checkbox-close':
'checkbox-filed':
'checkbox-notFiled':
arrStr += key[0] + '=';
arrStr += key[1][0].key + '&';
Here is an example I just made: https://jsfiddle.net/BrandonQDixon/surwf7gd
The script below will loop through the keys of an object and convert them to GET style parameters, which is what your request looks like. I made it a function so you can directly call it on an object.
This will also work recursively, if your object has nested objects, but understand that if nested objects have some of the same keys (or there are duplicates in general), they will both be added to the string.
/**
* This will turn an object into a GET style parameter
* This scans recursively if 2nd param is set to true, but "flattens" every property into one string, so this may cause some overriding
* This will encode the keys and values if 3rd param is set to true
*/
function paramatize(obj,recursive = true,encode = true) {
let str = "";
let len = Object.keys(obj).length
let i = 0;
for (let key in obj) {
i++;
if (typeof obj[key] === 'object' && recursive) {
str += paramatize(obj[key]);
} else {
let nKey = (encode)?encodeURIComponent(key):key;
let nValue = (encode)?encodeURIComponent(obj[key]):obj[key];
str += nKey+"="+nValue;
}
if (i < len) {
str += "&";
}
}
return str;
}

How to parse nested JSON in Javascript?

I am trying to parse and show JSON data (product catalog) using XMLHttpRequest method. I am able to display the brands and their names, but not able to showcase list of products progmatically.
Here is the sample JSON request:
{
"products": {
"laptop": [{
"brand": "sony",
"price": "$1000"
}, {
"brand": "acer",
"price": "$400"
}],
"cellphone": [{
"brand": "iphone",
"price": "$800"
}, {
"brand": "htc",
"price": "$500"
}],
"tablets": [{
"brand": "iPad",
"price": "$800"
}, {
"brand": "htc-tab",
"price": "$500"
}]
}
}
Right now I am using following code to show data in tabluar form:
function loadJSON() {
var data_file = "http://localhost/AJAX/productcatalog.json";
var http_request = new XMLHttpRequest();
http_request.onreadystatechange = function () {
if ((http_request.readyState == 4) && (http_request.status == 200)) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
data = '<table border="2"><tr><td>Type</td><td>Brand</td><td>Price</td></tr>';
var i = 0;
debugger;
for (i = 0; i < jsonObj["products"].laptop.length; i++)
{
obj = jsonObj["products"].laptop[i];
data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
}
for (i = 0; i < jsonObj["products"].cellphone.length; i++)
{
obj = jsonObj["products"].cellphone[i];
data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
}
for (i = 0; i < jsonObj["products"].tablets.length; i++)
{
obj = jsonObj["products"].tablets[i];
data = data + '<tr><td>laptop</td><td>' + obj.brand + '</td><td>' + obj.price + '</td></tr>';
}
data += '</table>';
document.getElementById("demo").innerHTML = data;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
Question What is the way to fetch product list , i.e. products, cellphone and tablets ? Right now I have hardcoded that in order to fetch complete list of brands. Please advice. (I want to use plain javascript and not jquery)
Thanks!
It sounds like what you're missing is the "How do I iterate over an object when I don't know all the keys".
An object is a set of key, value pairs. You can use for/in syntax: for( var <key> in <object> ){} to get each key.
For your use case it might be something like:
var products = jsonObject['products'];
for( var productName in products ){
//productName would be "laptop", "cellphone", etc.
//products[productName] would be an array of brand/price objects
var product = products[productName];
for( var i=0; i<product.length; i++ ){
//product[i].brand
//product[i].price
}
}
In practice, I might use something a little less verbose, but this makes it easier to understand what is going on.
To achieve the expected i have used for loop and HTML DOM createElement() Method
var product_catalog = {
"products": {
"laptop": [{
"brand": "sony",
"price": "$1000"
}, {
"brand": "acer",
"price": "$400"
}],
"cellphone": [{
"brand": "iphone",
"price": "$800"
}, {
"brand": "htc",
"price": "$500"
}],
"tablets": [{
"brand": "iPad",
"price": "$800"
}, {
"brand": "htc-tab",
"price": "$500"
}]
}
};
var output = document.querySelector('#product tbody');
function build(JSONObject) {
/**get all keys***/
var keys = Object.keys(JSONObject);
/**get all subkeys***/
var subkeys = Object.keys(JSONObject[keys]);
console.log(subkeys);
/**loop sub keys to build HTML***/
for (var i = 0, tr, td; i < subkeys.length; i++) {
tr = document.createElement('tr');
td = document.createElement('td');
td.appendChild(document.createTextNode(subkeys[i]));
tr.appendChild(td);
output.appendChild(tr);
}
};
build(product_catalog);
HTML:
Coepen URL for reference- http://codepen.io/nagasai/pen/xOOqMv
Hope this works for you :)
Look at this example:
var x = data.key1.children.key4;
var path = "data";
function search(path, obj, target) {
for (var k in obj) {
if (obj.hasOwnProperty(k))
if (obj[k] === target)
return path + "['" + k + "']"
else if (typeof obj[k] === "object") {
var result = search(path + "['" + k + "']", obj[k], target);
if (result)
return result;
}
}
return false;
}
//Then for evry node that you need you can call the search() function.
var path = search(path, data, x);
console.log(path); //data['key1']['children']['key4']
I think this is what you're asking about, you can use Object.keys to get the properties of an object, then loop through them afterward.
var data = {
"products": {
"laptop": [{
"brand": "sony",
"price": "$1000"
}, {
"brand": "acer",
"price": "$400"
}],
"cellphone": [{
"brand": "iphone",
"price": "$800"
}, {
"brand": "htc",
"price": "$500"
}],
"tablets": [{
"brand": "iPad",
"price": "$800"
}, {
"brand": "htc-tab",
"price": "$500"
}]
}
}
var typesOfProducts = Object.keys(data.products)
console.log(typesOfProducts)
document.getElementById('output').textContent = typesOfProducts.toString()
//Then, to loop through
var i = -1,
len = typesOfProducts.length
function handleProduct(productType) {
console.log("This is the " + productType + " data.")
console.log(data.products[productType])
}
while (++i < len) {
handleProduct(typesOfProducts[i])
}
<div id="output"></div>
It sounds like what you're looking for is just an array of the keys of the "products" object. Example:
Products: ["laptop", "cellphone", "tablets"];
If so, I would just run your json object through javascript's Object.keys() method.
var jsonObj = JSON.parse(http_request.responseText);
var products = Object.keys(jsonObj.products);
// products = ["laptop", "cellphone", "tablets"];

jsTree JSON issue [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I am working on some project module where i am using jstree.js plugin.
I am getting following JSON via web service call:
[
{
"name":"Folder1",
"attributes": {
"SubFolder1-1":"value1-1",
"SubFolder1-2":"value1-2",
...
"SubFolder1.7":"value1-7",
"SubFolder1.8":"value1-8"
}
}, {
"name":"Folder2",
"attributes": {
"SubFolder2-1":"value2-1"
}
}, {
"name":"Folder3",
"attributes": {
"SubFolder3-1":"value2-1"
}
}
]
But jsTree.js is not accepting the JSON format, It accept following format:
{
"data" : "node_title",
"attr" : {
"id" : "node_identificator",
"some-other-attribute" : "attribute_value"
},
"children" : [ /* an array of child nodes objects */ ]
}
Our approach:
var new_avatar = new Array();
new_avatar = data.attributeSets;
// Hardcoded data for JSTree
var dirn = {};
var final_child = {};
dirn = "[";
final_child = "[";
for (var info in new_avatar) {
for (var detailInfo in new_avatar[info].attributes) {
ckey = detailInfo; // Key
cval = new_avatar[info].attributes[detailInfo]; // Key => Value
final_child += '{ "data": "' + ckey + '",';
final_child += ' "attr": { "rel":"directory" },';
final_child += ' "children": [ "' + cval + '" ] },';
}
}
final_child = final_child.substring(0, final_child.length - 1); //removing last comma so it would be a valid JSON
final_child += " ] "; //final close to this JSON
for (var info in new_avatar) {
dirn += '{ "data": "' + new_avatar[info].name + '" ,';
dirn += ' "attr": { "rel":"directory" }, ';
dirn += ' "children": ' + final_child + " }, ";
// Putting final_child in so it will build level 2 + level 3 (level 3 child is just value declared in final_child children above)
}
dirn = dirn.substring(0, dirn.length - 2); // removing whitespace + comma
dirn += " ] "; // this is main tree data var end box
dirn = $.parseJSON(dirn); // parse the whole dirn variable so it would be an array and ready to feed to jstree.
$("#tree2").jstree({
plugins: ['themes', 'json_data', "ui"],
json_data: {
"data": dirn,
},
themes: {
theme: 'default'
},
checkbox: {
real_checkboxes: true,
two_state: true
},
"types": {
"types": {
"disabled": {
"check_node": false,
"uncheck_node": false
},
"directory": {
"check_node": false,
"uncheck_node": false
}
}
}
});
Current Output:
Showing error that json is not valid string.
Expected Output:
I got the solution and is working fine now. Thanks you all for showing interest.
var new_avatar = new Array();
new_avatar = data.attributeSets;
var dirn = {};
var final_child = {};
var nodeChildren = {};
//Collect children for each node
for (var info in new_avatar) {
final_child = "[";
for (var detailInfo in new_avatar[info].attributes) {
ckey = detailInfo; // Key
cval = new_avatar[info].attributes[detailInfo]; // Key => Value
final_child += '{ "data": "' + ckey + '",';
final_child += ' "attr": { "rel":"directory" },';
final_child += ' "children": [ "' + cval + '" ] },';
}
final_child = final_child.substring(0, final_child.length - 1); //removing last comma so it would be a valid JSON
final_child += " ] "; //final close to this JSON
nodeChildren[info] = final_child;
}
// Attached collected nodes to respective parents
dirn = "[";
for (var info in new_avatar) {
dirn += '{ "data": "' + new_avatar[info].name + '" ,';
dirn += ' "attr": { "rel":"directory" }, ';
dirn += ' "children": ' + nodeChildren[info] + " }, "; //putting final_child in so it will buld level 2 + level 3 (level 3 child is just value declared in final_child children above)
}
dirn = dirn.substring(0, dirn.length - 2);
dirn += " ] ";
dirn = $.parseJSON(dirn);
$("#tree2").jstree({
plugins: ['themes', 'json_data', "ui", "dnd"],
json_data: {
"data": dirn,
},
themes: {
theme: 'default'
},
checkbox: {
real_checkboxes: true,
two_state: true
},
"types": {
"types": {
"disabled": {
"check_node": false,
"uncheck_node": false
},
"directory": {
"check_node": false,
"uncheck_node": false
}
}
}
});

Categories