I'm trying to take a jSON encoded string out of my database and loop through the items but I'm having some difficulty. Here's the string in the database:
["volunteers","seat_dedication_program","memberships"]
And here is the code:
//Looks for _checkbox when looping through my database fields (object dbVals) and turns it into a true jQuery array if it finds it.
if( key.search(/_checkbox/i) > 0 ) var arr = $.makeArray(dbVals[key]);
//If it is an array, loop through the array values and show them
if($.isArray(arr)==true){
$.each(arr, function(i, n){
alert(i + " : " + n);
});
}
What I want is this:
//alert
0 : volunteers
//alert
1 : seat_dedication_program etc...
What I'm getting is this:
//alert
0 : ["volunteers","seat_dedication_program","memberships"]
I think I've included all relevant data. Can anyone help me figure out why this is happening?
Thanks.
Using $.makeArray(..) is giving you an array where the only element is the string you gave it. You need to parse the string into a JavaScript object. Use the JSON2.js library to parse then your code would look something like this.
var arr = JSON.parse(dbVals[key]);
if($.isArray(arr)==true){
$.each(arr, function(i, n){
alert(i + " : " + n);
});
}
Just use a regular for loop:
for (var i=0; i<arr.length; i++) {
var n = arr[i];
alert(i + " : " + n);
}
or for large arrays, the slightly optimized:
for (var i=0,l=arr.length; i<l; i++) {
var n = arr[i];
alert(i + " : " + n);
}
or if you really hate for loops:
Array.prototype.each = function (callback) {
for (var index=0,l=this.length;index<l;index++) {
var item = this[index];
// index is second arg since it's optional
callback(item,index);
}
}
arr.each(function(n,i){
alert(i + " : " + n);
});
but I'd recommend the for loop to avoid clashing with library modifications or when Firefox suddenly decide to implement its own each method for arrays (some libraries have already been bitten by this).
Related
[{"id":"1","name":"Bangalore"},{"id":"3","name":"Mysore"}]
I tried using the below code but its not giving me any output
var obj=jQuery.parseJSON(response); // now obj is a json object
alet(obj.id);
$("#state").html("<option value='"+ obj.id +"'>'"+ obj.name +"'</option>");
$("#state").next().next().html("<li rel='"+ obj.id +"'>"+ obj.name +"</li>");
Your JSON is a JSON array containing two objects. Therefore, you need to read it as an array first, before accessing the id:
alert(obj[0].id);
To loop all, you will write something like this:
for(var i = 0; i < obj.length; i++){
console.log("ID: " + obj[i].id);
};
Loop through array
var response=jQuery.parseJSON(response);
var li='';
for(var i=0;i<response.length;i++){
li=li+ "<option value='"+ response[i].id +"'>'"+ response[i].name +"'</option>";
}
$("#state").html(li);
It overlapping lines
I try to show many links between nodes by multi array (Source,Target,Value)
But It's not display.It overlapping lines.
[My Example] http://bl.ocks.org/Lovekiizzk/90cbfb9d8ee7fe9baa26
See in the knet2.json.
{
"nodes":[
{
"name":"Novak_Djokovic",
"thumbnail":"http:\/\/commons.wikimedia.org\/wiki\/Special:FilePath\/Flickr_-_Carine06_-_Novak_Djokovic_(4).jpg?width=300",
"uri":"http:\/\/dbpedia.org\/resource\/Novak_Djokovic",
"group":1},
{
"name":"Rafael_Nadal",
"thumbnail":"http:\/\/commons.wikimedia.org\/wiki\/Special:FilePath\/Rafael_Nadal_January_2015.jpg?width=300",
"uri":"http:\/\/dbpedia.org\/resource\/Rafael_Nadal",
"group":1},
{
"name":"Grand_Slam_(tennis)",
"thumbnail":null,
"uri":"http:\/\/dbpedia.org\/resource\/Grand_Slam_(tennis)",
"group":1},
{
"name":"Toni_Nadal",
"thumbnail":"http:\/\/commons.wikimedia.org\/wiki\/Special:FilePath\/Toni_Nadal.jpg?width=300",
"uri":"http:\/\/dbpedia.org\/resource\/Toni_Nadal",
"group":0},
{
"name":"Australian_Open",
"thumbnail":"http:\/\/commons.wikimedia.org\/wiki\/Special:FilePath\/Australian_Open_2007_Night_Session.JPG?width=300",
"uri":"http:\/\/dbpedia.org\/resource\/Australian_Open",
"group":0},
{
"name":"Tennis_at_the_2008_Summer_Olympics_\u2013_Men's_singles",
"thumbnail":"",
"uri":"http:\/\/dbpedia.org\/resource\/Tennis_at_the_2008_Summer_Olympics_%E2%80%93_Men's_singles",
"group":0},
{
"name":"The_Championships,_Wimbledon",
"thumbnail":"http:\/\/commons.wikimedia.org\/wiki\/Special:FilePath\/Spencer_gore.jpg?width=300",
"uri":"http:\/\/dbpedia.org\/resource\/The_Championships,_Wimbledon",
"group":0},
{
"name":"Big_Four_(tennis)",
"thumbnail":"http:\/\/commons.wikimedia.org\/wiki\/Special:FilePath\/R_federer.jpg?width=300",
"uri":"http:\/\/dbpedia.org\/resource\/Big_Four_(tennis)",
"group":0}
],
"links":[
{"source":1,"target":3,"prop":"coach","value":"coach"},
{"source":4,"target":2,"prop":"title","value":"title"},
{"source":4,"target":0,"prop":"menCurrent","value":"menCurrent"},
{"source":3,"target":1,"prop":"coachplayers","value":"coachplayers"},
{"source":5,"target":0,"prop":"bronze","value":"bronze"},
{"source":5,"target":1,"prop":"gold","value":"gold"},
{"source":5,"target":1,"prop":"goldMedalist","value":"goldMedalist"},
{"source":5,"target":0,"prop":"bronzeMedalist","value":"bronzeMedalist"},
{"source":6,"target":0,"prop":"menCurrent","value":"menCurrent"},
{"source":6,"target":2,"prop":"title","value":"title"},
{"source":7,"target":0,"prop":"caption","value":"caption"},
{"source":7,"target":1,"prop":"caption","value":"caption"},
{"source":3,"target":2,"prop":"coachtournamentrecord","value":"coachtournamentrecord"}
]
}
Some relation below.
{"source":5,"target":1,"prop":"gold","value":"gold"},
{"source":5,"target":1,"prop":"goldMedalist","value":"goldMedalist"},
My example don't show relation. It overlapping lines.
Please tell me why.
https://jsfiddle.net/71yrnaxe/5/
Your lines overlap because links connecting the same nodes have the same end and start points, what you need is some way to distinguish them. This is a bit hacky, but what it does is look through the links and give links with the same nodes different indexes in .multiLinkIndex -->
var mlink = d3.map();
graph.links.forEach (function(link) {
var key = link.source+"-"+link.target;
var i = mlink.has(key) ? mlink.get(key) + 1 : 0;
mlink.set (key, i);
link.multiLinkIndex = i;
});
then, when drawing the links we use this info to draw arcs of different radii between the nodes. The exact formula will need tinkering with I think but you can see in the fiddle the links are resolved individually. -->
var domLinks = [];
link.attr("d", function(d,i) {
domLinks[i] = this;
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy) / (d.multiLinkIndex + 1) ;
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
The really hacky bit is using the link elements (stored in domLinks) to calculate positions for the link text elements halfway along the curved links, rather than halfway between the nodes, because these would still overwrite each other. Uses some code adjusted from http://bl.ocks.org/mbostock/1705868
linkText
/*
.attr("x", function(d) {
return ((d.source.x + d.target.x)/2);
})
.attr("y", function(d) {
return ((d.source.y + d.target.y)/2);
})
*/
.attr("transform", function(d,i) {
var domLink = domLinks[i];
var l = domLink.getTotalLength();
var p = domLink.getPointAtLength(l/2);
return ("translate ("+p.x+","+p.y+")");
})
;
I have a json response from php to ajax. The thing is depending on the value entered in a text box the number of json arrays vary. Example: sometimes it may return {"count1":10, "ccc1":30} and sometimes like this {"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}. I extract the value in jquery this way:
success: function(response){
var count = response.count1;
//do something
}
But now since the number of counts are different I used a loop. Question is I can figure out how many of them I am receiving but how can I process them? The var count = response.count needs to be specific right? I cannot just concate any strings like this:
var count = 0;
while(something){
count = count + 1;
var str = "count"+count;
var whatever = response.str;
}
So, can someone please help me with a suitable solution in this case?
You are on the right track there. Something like this should work for you.
var i = 1;
while(response['count' + i]) {
var count = response['count' + i++];
}
You can access the properties as if they were array indices. so response['count'+i] works.
Loop through all properties and add them in a variable like following.
var response = { "count1": 10, "ccc1": 32, "count2": 40, "ccc2": 123, "count3": 32, "ccc3": 21 };
var count = 0;
for (var prop in response) {
if (prop.startsWith('count'))
count += response[prop];
}
console.log(count);
To retrieve all values use jQuery $.each function.
var data_tmp = '{"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}';
var data = $.parseJSON(data_tmp);
$.each(data, function(k,val){
if(k.toLowerCase().indexOf("count") >= 0){
$('.wr').append('<div>' + val + '</div>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wr"></div>
success: function(response){
var count = response.count1;
var object = JSON.parse(response);
alert(object.length);
for (i = 0; i < object.length; i++) {
console.log(object[i]);
}
}
I have a problem with jQuery to obtain each value from jSon string and modify a div or span or other id with value obtained from a jSon string.
At the start of each PHP file i have an SQL request generate an hidden input with a jSon string as value. This is for multilanguage for example in english the generated string is
<input type="hidden" id="page_json_language_home" value='{
"label_title":"My WebSite",
"label_settings":"Settings",
"label_subscription":"Subscription"
}' />
for french :
<input type="hidden" id="page_json_language_home" value='{
"label_title":"Mon site web",
"label_settings":"Parametres",
"label_subscription":"Abonnement"
}' />
this is work fine !
After that i have a javascript using jquery to match each label_xxx with value
i have many html code like this
<title id="label_title></title>
<div id="label_settings"></div>
or
<span id="label_subscription"></span>
This is my (partial) code in my javascript file i called to obtain the json string from hidden input :
var _getPageJsonLanguage = function(id) {
if (!id)
id = "page_json_language";
else
id = "page_json_language_" + id;
var json = $("#" + id).val();
var data = bsc.data.jsonParse(json);
return data;
};
This is work fine too !
The code in problem is :
data_language = bsc.page.getPageJsonLanguage("home");
var j = 0;
var language = [];
for (i in data_language) {
console.log("i in language = " + i);
language[j] = i;
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
The result can i obtain in browser 1) undefined for each label or 2) label_xxx for each label_xxx
I need help to access each value of each label_xxx .
I can't obtain the value, this is my last try....
I believe the problem is in your for in loop, you never actually grab the value, only the key:
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i]; //changed this line to actually grab the value
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
If you are receiving undefined, it may be due to the JSON not being parsed correctly. Since your using jQuery, you can always run $.parseJSON(json) to be sure.
Fiddle accessing your JSON in a for in loop and logging: http://jsfiddle.net/tymeJV/CKBLc/1/
I hope this will work -
var data_language = JSON.parse($("#page_json_language_home").val());
var language = [];
var j = 0;
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i];
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
I have a PHP file which only return an array with the drivers and a url:
{"drivers":[{"marco":[0],"luigi":[123],"Joan":[2444],"George":[25]}, {"marco":[23],"luigi":[3],"Joan":[244],"George":[234]}],"url":"google.es"}
Is the json correctly structured?
And I'm trying to get the result using jQuery and AJAX by this way:
$.getJSON('calculate.php&someparams=123', function(data) {
alert("url - " + data.url);
var arr = data.drivers;
for (var i = 0; i < arr.length; i++) {
alert(arr[i] + " - " + arr[i][0]);
}
});
I see the first alert() with the url, but the second one does not works...
What am I doing wrong?
If you need more info let me know and I'll edit the post.
The drivers is not an array, it is an object, you use $.each to iterate through the object elements.
$.getJSON('calculate.php&someparams=123', function(data) {
$.each(data.drivers, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
})
});
That's an object, not an array. It has named properties, not numerical indexes.
You need a for in loop to loop over the properties.
drivers is an object. Not an array.
How about this?
var json_string = '{"drivers":{"marco":[0],"luigi":[123],"Joan":[2444],"George":[25]},"url":"google.es"}';
var obj = jQuery.parseJSON(json_string);
alert(obj.url);