Looping through multilayer json Jquery - javascript

Hi i'm quite new to jquery and json so please bear with me. I have searched the forums and tried a lot of different things to solve my problem.
I'm trying to loop through a multilayer JSON file form Freebase.
$.getJSON(service_url + topic_id + '?callback=?', params, function(topic) {
$("#free").append('<h3>Description</h3><p>'+topic.property['/common/topic/description'].values[0].value+'</p>');
$("#title").prepend('<h2>'+topic.property['/type/object/name'].values[0].value+'<span><a class="socila-link" style="color:#3b5998;" href="'+topic.property['/common/topic/social_media_presence'].values[0].value+'"> <i class="icon-facebook-sign"></i></a><a class="socila-link" style="color:#0084B4" href="'+topic.property['/common/topic/social_media_presence'].values[2].value+'"> <i class="icon-twitter-sign"></i></a></span></h2>')
$("#fb-span1").append('<p><strong>Official Website: </strong>'+topic.property['/common/topic/official_website'].values[0].value+'</p>');
$("#fb-span1").append('<p><strong>Genre: </strong>'+topic.property['/music/artist/genre'].values[0].text+'</p>');
$("#fb-span1").append('<p><strong>Founded: </strong>'+topic.property['/music/artist/active_start'].values[0].text+'</p>');
$("#fb-span1").append('<p><strong>Hometown: </strong>'+topic.property['/music/artist/origin'].values[0].text+'</p>');
$.each(topic.property, function(i, val) {
$("#fb-span1").append('<p><strong>Genre: </strong>'+val['/music/artist/genre'].values['text']+'</p>');
});
I have no problems getting the result if i enter the value like [0], but i cant seem to loop through it.Nothing gets returnet

Aside from the getJSON call you don't need any jQuery to do this. You can just access the JSON data as regular Javascript arrays and dictionaries. So to output multiple values from the array of "Genre" property values you can just use a for loop like this:
for (var i=0; i<topic.property['/music/artist/genre'].values.length; i++) {
var val = topic.property['/music/artist/genre'].values[i];
$("#fb-span1").append('<p><strong>Genre: </strong>'+val['text']+'</p>');
}

Related

Passing a json array to javascript function in a jade rendered page

I have a json array being passed to a jade template.
This template then runs through the array adding rows to the html output.
However a new requirement no needs that json object to be passed to a javascript function, so I tried:
- var json = JSON.stringify(rows);
input.medium.success.button.error(type='submit', id='update_details', value= sendCommandLabel, onclick='sendCommand(' + json + ')')
which gives the following output (the full array omitted from brevity):
<input type="submit" id="update_details" value="Send Command" onclick="sendCommand([{"id":"id1;,"param1":value1, ... "}])">
Which is not useful as I am want to use this output in the javascript function and as it stands I can't consume it.
I am hoping I am missing something simple as my other option is to recreate the json array by looping through the objects in the renderer to recreate it!
UPDATE: I modified the code so instead of passing the array to the function, the array is hardcoded into the function while the jade page was being compiled. So this:
function sendStopCommandToAllSensors()
{
var hardcode = !{JSON.stringify(rows)};
became
function sendStopCommandToAllSensors()
{
var hardcode = [{"id":"id1", ... }, {"id":"id2", ... }];
But that still didn't work.
Puzzlingly adding a couple of simple alerts in there showed that there was the correct number of objects (later confirmed that there by cutting and pasting the resultant string directly into code and then manually adding a third object).
alert(hardcode.length); // displays 2
alert("rows: " + hardcode); // displays [object Object],[object Object]
Which is why in the loop that follows the
for (var row in hardcode)
{
alert("row: " + row); // displays 0 or 1, not an object
if (row.active == 1)
{
alert("Reached here"); // never reached
the final line is never reached.
UPDATE II: By stringifying hardcode I can output the human readable json.
alert("rows: " + JSON.stringify(hardcode));
Why is the code not seemingly parsing the array correctly and what to I do need to do correct it?
UPDATE III: I now having it working by using a two step traditional loop and assignment.
for (var i=0; i<rows.length; i++)
{
var row = rows[i];
So the question seems to be now, why didn't the for..in loop work as expected?
I am new to this, but I was going through similar problem I think.
But I am totally ok with JSON.stringify method, which was your first solution. It looks ugly in generated hmtl, but I found it useful in my case.
At least I think I understood it right and you are not trying to do some kind of magic what I can't absorb yet.
if
rows=[{id:id,param:param},{id:id2,param:param2}]
JADE:
- var json = JSON.stringify(rows);
input(type='submit', onclick='myFunction(' + json + ')')
JS:
function myFunction(myRows) {
console.log(myRows[0].id);
console.log(myRows[0].param);
console.log(myRows[1].id);
console.log(myRows[1].param);
.
.
at least it is ok in what I am working on.
I hope I didn't wrote pile of nonsense :)

sending javascript array to jsp using ajax

So, I'm working on a MULTIPLE CHOICE QUESTION entry page and i want to handle it completely with ajax. I want to be flexible with the number of options the question has.
Here's the jquery part:
$("#QuestionModPageSubmitButton").click(function(){
var QuesDesc=$("#QuesDesc").val();
var Options=[];
var QuestionId=$("#QuestionId").attr("data-id");
var CorrectOption=$('input[type="radio"]:checked').val();
var TotalOptions=$("#TotalOptions").attr("data-total");
var SubjectId=$("#SubjectId").attr("data-id");
for(var i=0;i<TotalOptions;i++)
{
Options.push($("#Option"+i).val());
}
$.ajax({
type:"POST",
url:"ajax/ModifyQuestion.jsp",
data:{
Subject:SubjectId,
QID:QuestionId,
Question:QuesDesc,
OptionValues:Options,
Correct:CorrectOption,
TotalOptions:TotalOptions},
});
});
I want to sent the Options Array to the jsp page "ModifyQueston.jsp".
Here's the jsp code i use for reading the sent data:
int SubjectId=Integer.parseInt(request.getParameter("Subject"));
int QuestionId=Integer.parseInt(request.getParameter("QID"));
String Question=request.getParameter("Question");
String[] Options=request.getParameterValues("OptionValues");
int CorrectOption=Integer.parseInt(request.getParameter("Correct"));
int TotalOptions=Integer.parseInt(request.getParameter("TotalOptions"));
But with these codes I'm not able to read the array in the jsp page. I get NullPointerException when i try to read the length of the Options array or when i try to read values by providing index.
I guess the script part of sending the data to jsp is fine. So the question is how to get it into jsp page.
I tried converting the array into a single string by separating each value with a '-' and then reading it using getParameter() function and then using split() function to separate it back to Array.
Script:
var OptionsString="";
for(var i=0;i<TotalOptions;i++)
{
Options.push($("#Option"+i).val());
OptionsString+=(Options[i]+((i<TotalOptions-1)?" - ":" "));
}
JSP:
String[] Options=(request.getParameter("OptionValues")).split("-");
It works fine. But I don't want to do it this way because if any of the options already contains '-' the Code will crash.
So, how to get this done?
Okay, so after a couple of weeks of research I found out a way to send the array from js to jsp. The previous code needed just a little modification.
Here's the js part which needed modification.I just had to add brackets as in arrays, in the data section.
$.ajax({
type:"POST",
url:"ajax/ModifyQuestion.jsp",
data:{
Subject:SubjectId,
QID:QuestionId,
Question:QuesDesc,
Correct:CorrectOption,
"Options[]":Options
},
});
Notice that I wrote Options as "Options[]". This makes jsp understand that the variable being sent is an array.
Now, the jsp page didn't really require much modification.
String[] Options=request.getParameterValues("Options[]");
And any further operations can be performed as normal strings.
So, yeah that worked for me!..
You can sending multiple value by ajax. From the controller end (for spring framework) you just save it in a string. the data will bind with comma separated values. to do that, you need an array from javascript end, i mean your jsp side.
for checkbox you can use:
var idVal = [];
var i = 0;
$('.case:checked').each(function() {
idVal[i] = $(this).val();
i++;
});
From controller side you can get the value:
String[] id = req.getParameter("id_").split(",");
As the same way you can do this for dropdown (options).This is worked for me when using spring framework.
Thanks.

How to parse a JSON array

new here and hit a roadblock, been searching but can't find the answer with my skill set. Task is pretty simple, I want to parse this http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json which is from a weather station. I have used the W3C tutorial but just can't seem to parse this file, but http://json.parser.online.fr has no problem. All the looping parse examples just give me alert after alert.
All I want is the ability to select temp[0] (out of god knows how many) for example via javascript and have it display on a website. I'm really lost, tried searching and if I've missed the goldmine then my bad. Thanks!
Example code
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌​43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌​43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.temp[0];
First, you need to parse the incoming string as below:
temp_arr = JSON.parse(json_string);
Just loop over the temp_arr array, and in each iteration of loop you'll have one object (tobj). For example, like this:
{"humidity":"40.9000","stationtime":"2014-07-06 21:21:03","temp":"22.6000","timestamp":"2014-07-06T11:20:27.231Z"}
All you have to do is, access it like tobj.temp and use it to display on page.
I have written a jquery implementation at: http://jsfiddle.net/DNH5n/2/
Jquery makes working with JSONP much easier heres an example (http://jsfiddle.net/icodeforlove/9mBsr/)
$.getJSON('http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?callback=?', function (data) {
data.forEach(function (item) {
$('body').append(JSON.stringify(item));
});
})
update again
heres another example using your code (http://jsfiddle.net/icodeforlove/9mBsr/2/)
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj[0].temp;

Retrieving the last set of key values from array using JQuery

complete noob currently trying to complete a Uni assignment. We are creating a web app using HTML, css and JQuery. I've searched the web for an answer but can't quite figure out what I'm supposed to do.
I have set up a page where users can type in details for a shift, when they submit it, the data is pushed onto an array stored in localStorage using JSON stringify. That part works great and here it is:
var shift = {'location':$('#shift_location').val(), 'start_time':$('#shift_start_time').val(), 'end_time':$('#shift_end_time').val()};
var shift_list = JSON.parse(localStorage.shift);
shift_list.push(shift);
localStorage.shift = JSON.stringify(shift_list);
However I then need to take the last 'shift_location' 'shift_start_time' and 'shift_end_time' that has been added and stick it in a div on the page.
This is what I have come up with so far:
var result = JSON.parse(localStorage.shift);
$.each(result, function(k, v) {
$('.current_shift').text(k + ":" + v);
});
However, all that appears on the page is: 0:[object Object].
Any ideas on how to sort this out would be great. Like I said I'm a complete noob and this is my first time posting on here so apologies in advance if I've missed out any important bits of code or framed the question incorrectly.
Thanks
James
You have an array of objects, you have to get the last object in the array first :
var result = JSON.parse(localStorage.getItem('shift'));
var obj = result.pop();
$('.current_shift').text(obj.start_time + ":" + obj.end_time);
This is an Array shift_list.
So it looks like locationStorage.shift is an array. That is why the k is an integer. Try this:
$.each(result, function(k, v) {
$('.current_shift').text(v.location);
});
You will see that it is an object since your shift is stored in Objects. For debugging you can do this:
$.each(result, function(k, v) {
console.log(v);
$('.current_shift').text(v.location);
});
Open Chrome, and look at the console, there you will see your objects.

pass JS Objects in URL

I have already searched from this question in SO. But none of the answers worked for me, so I am posting this once more in the hope to find an answer that works for me.
Is there a way to pass JS/JSON objects through URL? Suppose I have a JS Object like so:
var jObj = {"color":"red","shape":"square"}
Now suppose I want to pass it to a URL like so:
window.open("/process/jObj"); //here I want the var defined above to be passed
I tried various options like JSON.stringfy, encodeURIComponent, escape..but I am not able to pass it around. Any idea how this can be achieved in pure JS?
I would like to pass it so that in the next page (process.php) such that there I can get the values of jObj and use it for further processing. Basically I am looking for an option where I can pass the object to the effect of ?color=red&shape=square without having to squash and reformat the object too much
Here is one thing you can do
var jObj = {"color":"red","shape":"square"}
var urlParam = []
for (var i in jObj){
urlParam.push(encodeURI(i) + "=" + encodeURI(jObj[i]));
}
window.open("/process/?" + urlParam.join("&"));
this should produce your result

Categories

Resources