I am trying to use the jqTree from http://mbraak.github.io/jqTree/#tutorial
my page is
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> Json Parser </TITLE>
<link rel="stylesheet" href="css/jqtree.css">
<script src="js/jquery-2.0.3.min.js"></script>
<script src="js/tree.jquery.js"></script>
<script type="text/javascript">
$(function() {
var data = [{"tweetText":"RT #dna: IPL spot-fixing: Jagmohan Dalmiya still clueless about N Srinivasan's return http://t.co/PwDniu8sJg","urlsMentioned":[],"usersMentioned":[{"userId":17710740,"screenName":"dna","userName":"dna"}],"source":"Twitter for Android","tweetId":362907208733827100,"reTweetCount":12,"reTweeted":true,"createdDate":"Thu Aug 01 12:06:35 UTC 2013","user":{"location":"","userId":24525170,"screenName":"varuntripathi1","userName":"varun","profileDescription":"","language":"en"},"reTweetedStatus":{"tweetText":"IPL spot-fixing: Jagmohan Dalmiya still clueless about N Srinivasan's return http://t.co/PwDniu8sJg","urlsMentioned":["http://dnai.in/bAoD"],"usersMentioned":[],"source":"Tweet Button","tweetId":362606709404991500,"reTweetCount":12,"reTweeted":false,"createdDate":"Wed Jul 31 16:12:31 UTC 2013","user":{"location":"India","userId":17710740,"screenName":"dna","userName":"dna","profileDescription":"We are India’s favourite English daily delivering news, views & analyses. Follow us for real-time news updates. PS: This Twitter feed is not operated by a bot.","language":"en"},"hashTags":[]},"hashTags":[]}]
$('#tree1').tree({
data: data
});
});
</script>
</HEAD>
<BODY>
<div id="tree1">
</div>
</BODY>
</HTML>
It does not show any value. but it is workinf fine for the data
var data = [
{
label: 'node1',
children: [
{ label: 'child1' },
{ label: 'child2' }
]
},
{
label: 'node2',
children: [
{ label: 'child3' }
]
}
];
even though both json are valid one. How would i solve this or any other js available to select the nodes of a json.
jsfiddle
Is there anyother js available to view the json.
Thanks in advance.
As you probably have already figured out, valid JSON != valid data.
You need to provide the constructor with data that corresponds to its requirements.
In the case of jqTree, that is
[
{
"label":"node 1",
"children": [
{
"label": "node 1.1"
},
{
"label": "node 1.2"
}
]
},
{
"label": "node 2"
}
]
etc.
So, you need a function to reformat the data, such as:
function formatData(arr) {
var label, data = [], obj, node;
if(!$.isArray(arr)) {
arr = [arr];
}
console.log(arr);
var l = arr.length, i;
for(i=0; i< l; ++i) {
node = {};
obj = arr[i];
node.label = obj.user.screenName + ": " + obj.tweetText + " (" + obj.createdDate + ")";
if(typeof obj.reTweetedStatus == "object") { //fetch children
node.children = formatData(obj.reTweetedStatus);
}
data.push(node);
}
return data;
}
which will return something like
[{
"label": "varuntripathi1: RT #dna: IPL...Jg (Thu Aug 01 12:06:35 UTC 2013)",
"children": [{
"label": "dna: IPL spot-fixing: Ja...Jg (Wed Jul 31 16:12:31 UTC 2013)"
}]
}]
This creates a tree that looks something like this:
Demo
On a side note, I believe that it will be difficult for you to do what you want with jqTree. It is relatively difficult to customize, in my view.
You can find more configurable jQuery tree widgets, such as jsTree or zTree in jQuery's plugin site.
I created a short example with zTree that produces a the following tree based on your data:
Demo
Your data variable is not a JSON, JSON is a formatted string that you can parse to get a get a javascript object in this case.
A proper JSON string of that object is: var jsonData = "[{"label":"node1","children":[{"label":"child1"},{"label":"child2"}]},{"label":"node2","children":[{"label":"child3"}]}]"
Although I haven't ever used jqTree, I typed your example in Plunker to check how tree work with the three types of data; you data, a json data get from javascript object and the object get from that json data.
http://plnkr.co/edit/Sw3BCigiU69jLkQkAw5U?p=preview
[{
"club":
{ "id":1,"name":"This is a team name"},
"members":
[
{"id":2,"name":"Test Name"},
{"id":3,"name":"Another Name"},
{"id":4,"name":"More Names"},
{"id":5,"name":"Cool Person"}]
}];
Put [ and ]
I have edited my answer, can u please try this
var data = [
"club":
[{"id":1,"name":"This is a team name"}],
"members":
[{"id":2,"name":"Test Name"},{"id":3,"name":"Another Name"},{"id":4,"name":"More Names"},{"id":5,"name":"Cool Person"}]
];
I tried by adding a extra brace around the json data returned from the server and worked
$.post(your_url, null, function (data) {
//add extra braces before binding to the tree
data = $.parseJSON("[" + data + "]");
$('#tree1').tree({
data: data,
autoOpen: true,
dragAndDrop: true
});
});
The following json data works.
var data = [
{
label: 'RT #dna: IPL spot-fixing: Jagmohan Dalmiya still clueless about N Srinivasan\'s return http://t.co/PwDniu8sJg',
children: [
{
label: 'IPL spot-fixing: Jagmohan Dalmiya still clueless about N Srinivasan\'s return http://t.co/PwDniu8sJg'
}
]
}
];
By the way, what do you want to show exactly in the tree?
Related
Can't fetch data from table I've just created in rethinkDB.
I've create a new table in retinkDB - items.
And fill it with data:
r.db('test').table('items').insert([
{name: 'qqq'},
{name: 'www'},
{name: 'eee'}
])
BUT .getList() never returns table's data:
client.record.getList('items') // '.getEntries()' always return []
I don't really understand why .getList('items') didn't return data from items table.
I assume that this is because entries structure: when you are create entry via deepstream, entry's structure be like:
[
...
{
"_d": {
"id": "qqq"
"name": 'qqq'
},
"_v": 0,
"ds_id": "qqq"
}
...
]
But mine structure is just:
[
{
"id": 'qqq'
"name": 'qqq'
}
]
My question is: How to create table with data in rethinkDB (via script) that would we worked with deepstream?
deepstream is designed to manage data for you. Simply by saying
var bmw = ds.record.getRecord( 'cars/bmw' )
deepstream will create a table called cars and store an entry with a primary key of bmw in it. You wouldn't be expected to create the table yourself.
I've find a solition.
First of all table should be created with proper primaryKey === "ds_id":
r.db('test')
.tableCreate('items',
{
primaryKey: 'ds_id'
})
And after that you have to insert data with deepstream-like structure:
r.db('test').table('items').insert([
{
"_d": {
"id": r.uuid(),
"name": "qqq"
},
"_v": 0,
"ds_id": r.uuid()
}
])
P.S. to make _d.id equal to ds_id use this:
r.db('test').table('items').forEach(function(c) {
return r.db('test').table('items').get(c('ds_id')).update(function(row) {
return {_d: {id: row('ds_id')}};
});
})
This is stupid but I don't know how to do it in more elegant way.
I'm sending a JSON array to a script for further processing. The JSON array contains a bunch of objects each of which contain a further array of objects. What I need to know is how to access values within those nested objects. So, for instance, if the script receives the following:
petlist = [
{"cats":[
{"catName":"Felix","catType":"British short haired"}
]
},
{"dogs":[
{"dogName":"Fido","dogType":"Labrador"}
]
},
{"fish":[
{"fishName":"Bob","fishType":"Goldfish"}
]
},
{"birds":[
{"birdName":"Polly","birdType":"Parrot"}
]
}
]
How would I then address, say, a) dogName, b) birdType, or c) the entire cats object?
Also, am I correct in my terminology here? As I understand it the stuff in square brackets is an array, while the stuff in curly braces is an object.
edit: I am building the JSON in Javascript and I then need to access the elements in a Jade template (in an 'each' loop)
Thanks
I changed your JSON a little bit because I think it was not very fun to work with. Basically I just loop through the objects thats why I thought you should have a key like name instead of dogName, catName and so on.
You can find the working example with Jade in this JSFiddle
HTML
<div id="jadeoutput"></div>
<pre id="jadeinput" style="display:none">
- console.log(petlist)
h1 List
ul.list
- for(var i in petlist)
li= "Item - "+ petlist[i].name
- for(var j in petlist[i].pets)
li= "Pet - " + petlist[i].pets[j].name + " " + petlist[i].pets[j].type
</pre>
JavaScript
$(function() {
var json = {
"petlist" : [
{
"name" : "cats",
"pets":
[
{ "name":"Felix","type":"British short haired"}
]
},
{
"name" : "dogs",
"pets":
[
{"name":"Fido","type":"Labrador"}
]
},
{
"name" : "fish",
"pets":
[
{"name":"Bob","type":"Goldfish"}
]
},
{
"name" : "birds",
"pets" :
[
{"name":"Polly","type":"Parrot"}
]
}
]};
$("#jadeoutput").html(jade.compile($("#jadeinput").html())(json));
});
I am not very strong with Javascript. I have a nested array which is a JSON representation of the backend data. It shows a list of proofs and the images used in each proof. Its looks like below:
var project = [{
"proof":"Proof_1",
"images":[
{
"image_id":"12469",
"name":"1911791794.jpg",
},
{
"image_id":"12470",
"name":"1911802897.jpg"
},
{
"image_id":"12471",
"name":"1911761073.jpg"
}
},
{
"proof":"Proof_2",
"images":[
{
"image_id":"12469",
"name":"1911791794.jpg",
},
{
"image_id":"12470",
"name":"1911802897.jpg"
}
}];
I want to add the image_count to each proof section,so that modified data structure looks like this:
var project = [{
"proof":"Proof_1",
"image_count": 3, //<----this is new property I want to add
"images":[
{
"image_id":"12469",
...
I checked some answers but because of my lack of understanding javascript iteration properly I am unable to get this done.
When I do:
for (var proof in project)
{
console.log(proof);
}
I just get 0,1,2...etc printed. I am not getting this, so I help someone in SO will help me understand how to add this property I want.
Thanks in advance.
You can take advantage of Array.prototype.map method:
project = project.map(function (item) {
item.image_count = item.images.length;
return item;
});
Working demo.
Also, as #Sebastian Lasse pointed out - you should name your array using plural form to avoid confusion (projects instead of project).
You can use .map or simple loop
var projects = [{
"proof": "Proof_1",
"images": [{
"image_id": "12469",
"name": "1911791794.jpg",
}, {
"image_id": "12470",
"name": "1911802897.jpg"
}, {
"image_id": "12471",
"name": "1911761073.jpg"
}]
}, {
"proof": "Proof_2",
"images": [{
"image_id": "12469",
"name": "1911791794.jpg",
}, {
"image_id": "12470",
"name": "1911802897.jpg"
}]
}];
projects = projects.map(function (element) {
element.image_count = element.images.length;
return element;
});
console.log(projects);
var len = projects.length, i;
for (i = 0; i < len; i++) {
projects[i].image_count = projects[i].images.length;
}
console.log(projects);
You could - after correcting the missing ] error in your JSON - do this :
project.forEach(function(proof) {
proof.image_count = proof.images.length;
})
demo -> http://jsfiddle.net/dLd8wvpb/
I have a json tree structure that is appended to by pressing invoke on this fiddle : http://jsfiddle.net/adrianjsfiddlenetuser/C6Ssa/4/
Press invoke multiple tiles on the fiddle & copy/paste the produced jSon intohttp://jsonlint.com/, the produced json is not valid
I need to produce this :
{
"nodes": [
{
"url": "asdfas",
"date": ""
},
{
"url": "asdfas",
"date": ""
},
{
"url": "asdfasfdasas",
"date": ""
}
]
}
Can this be amended so that multiple children can be added to the tree structure, I think I need to amend the var data somehow ?
Try:
var data = {nodes: []};
$("#add").on('click', function () {
data.nodes.push({
url: "some url",
date: new Date
});
$("#myDiv").text(JSON.stringify(data));
});
if not, I didn't understand your question ;)
http://jsfiddle.net/gY5yQ/
See if this helps http://jsfiddle.net/C6Ssa/12/
var data = [];
$("#add").click(add);
function add() {
data.push({
param1: "stuff",
param2:1,
param3:1
});
var sample = {};
sample.node = data
$("#myDiv").text(JSON.stringify(sample));
}
I have this XML structure that I wish to construct in JSON format using JavaScript - preferably using dot notation all the way if possible. :)
Here is the XML - note this is a pseudo structure, to keep it simple! :)
<Items>
<Item>
<Name>Item 1</Name>
<SubItems>
<Item>
<Name>Sub Item 1</Name>
</Item>
</SubItems>
</Item>
<Item>
<Name>Item 2</Name>
</Item>
</Items>
So, when I convert my JSON to XML (on the server), the output should be like above.
I need help getting started with this. I Google'd around and I couldn't find any examples on how to do this.
Thanks in advance!
EDIT: I am using NewtonSoft JSON for .NET to convert from JSON to XML!
EDIT 2: Ok, I figured out the Raw JSON structure to get the convertion to XML right - here it is:
var json = {
"Items":
{
"Item":
[
{
"Name": "Test 1" ,
"SubItems":
{
"Item":
[
{
"Name":"Test 1"
},
{
"Name":"Test 2"
}
]
}
},
{
"Name":"Test 2"
}
]
}
};
That will produce the exact same XML structure as defined above.
Now, how would I go about building this structure using dot notation?
EDIT 3: With the help of Nikhil & Darin, I figured it out, however this only answers the pseudo-question. However I will mark this as answered and create a new question. :)
EDIT 4: I posted my extension to the marked answer. :)
this should do it:
var items = [
{"name":"Item 1","subitems":[
{"name":"Subitem 1"}
]},
{"name":"Item 2"}
];
var items = [ ];
var item1 = { };
item1.Name = 'Item 1';
item1.SubItems = [ ];
var subItem = { };
subItem.Name = 'Sub Item 1';
item1.SubItems.push(subItem);
items.push(item1);
var item2 = { };
item2.Name = 'Item 2';
items.push(item2);
var json = {};
json.Items = {};
json.Items.Item = new Array();
var item1 = {};
item1.Name = "Test 1"
item1.SubItems = new Array();
var subItem1 = {};
subItem1.Item = new Array();
subSubItem1 = {};
subSubItem1.Name = "Test 1";
subSubItem2 = {};
subSubItem2.Name = "Test 2";
subItem1.Item.push(subSubItem1);
subItem1.Item.push(subSubItem2);
item1.SubItems.push(subItem1);
var item2 = {};
item2.Name = "Test 2";
json.Items.Item.push(item1);
json.Items.Item.push(item2);
Output of the above code is
{
"Items": {
"Item": [
{
"Name": "Test 1",
"SubItems": [
{
"Item": [
{
"Name": "Test 1"
},
{
"Name": "Test 2"
}
]
}
]
},
{
"Name": "Test 2"
}
]
}
}
that should do it :)
Nikhil answered the question, and has gotten the magic tick. :) - I am extending his answer with the code I wrote to get the result I was looking for.
My real problem, after receiving the answer to the pseudo problem, was that I have different item types in my structure, which all shared the Items root node.
Here is a pseudo example of how I solved the issue. Again, Nikhil's answer was the base of the solution, so many thanks to him :)
Say we have a rootnode, Fruits, and we have different types of fruit. Say, apple, and banana.
Here's how I got the JSON structure (and ultimately, the XML convertion output that I was needing):
// Create the JSON Object
var json = {};
// Create the Fruits Objects (Our root)
json.Fruits = {};
for (var i = 0; i < 3; i++){
// Pseudo condition
if (i == 0 || i == 1) {
// Make sure we have an Apple array
if(json.Fruits.Apple == undefined)
json.Fruits.Apple = [];
json.Fruits.Apple.push({
"Color": "Green"
});
} else {
// Make sure we have a Banana array
if (json.Fruits.Banana == undefined)
json.Fruits.Banana = [];
json.Fruits.Banana.push({
"Color": "Yellow"
});
}
}
This will output the following JSON:
{"Fruits":
{"Apple":
[
{"Color":"Green"},
{"Color":"Green"}
],
"Banana":
[
{"Color":"Yellow"}
]
}
}
And ultimately, the following XML:
<Fruits>
<Apple>
<Color>Green</Color>
</Apple>
<Apple>
<Color>Green</Color>
</Apple>
<Banana>
<Color>Yellow</Color>
</Banana>
</Fruits>