problem with iterating through the JSON object - javascript

In the code below, I tried iterating over the JSON object string. However, I do not get the desired output. My output on the webpage looks something like:-
+item.temperature++item.temperature++item.temperature++item.temperature+
The alert that outputs the temperature works well. The part where I try accessing the value by iterating through the JSON object string doesn't seem to work. Could some one help me out with fixing this?
Code
<body>
<script>
$.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2',
function(data) {
$.each(data.weatherObservations, function(i, item) {
$("body").append("+item.temperature+");
if (-i == 3-) return false;
});
alert(data.weatherObservations[0].temperature);
});
</script>
</body>

Don't use quotes within $("body").append("+item.temperature+"); in the .append() part.
should be
$(document.body).append(item.temperature);
Writting that expression with quotes like you did, just adds a string over and over. Java//Ecmascript interpretates anything withing quotes as a string literal.
Notice that I also replaced "body" with document.body. That has mostly performance // access reasons, so better karma.

Your code is iterating through, but you're appending "+item.temperature+", don't you want to do something like
$("body").append("Temp is " + item.temperature);
or
$("body").append(item.temperature);

"+item.temperature+" means a string which is "+item.temperature+"
"pre" + item.temperature + "post" will concatenate the variable to the strings.
$.getJSON('http://ws.geonames.org/weatherJSON?north=90&south=-9.9&east=-22.4&west=55.2',
function (data) {
$.each(data.weatherObservations, function (i, item) {
$("body").append(item.temperature + ",");
if (i == 3) return false;
});
alert(data.weatherObservations[0].temperature);
});

Related

How can you parse NON wellformed JSON (maybe using jQuery)

Is there a way to parse NON wellformed JSON, other than using eval?
The background is, that I'm using data tag values to draw a graph like this:
<div id="data" data-idata="[1,2,3]" data-sdata="['foo','bar','baz']"></div>
This works flawlessly with numeric values, these values are delivered as an array directly in jQuery data, no need to parse JSON here.
However, for the labels a string array is to be passed. eval can parse the string in sdata just fine, but JSON.parse and jQuery.parseJSON fail, because it's not wellformed JSON.
var $data = $("#data").data(),
values;
// use eval
out("#out", eval($data.sdata)); // works...
// use JSON.parse
try
{
values = JSON.parse($data.sdata);
} catch(e) {
// silent catch
}
out("#out1", values); // values is undefined
I put together a JsFiddle here to check the thing.
You get error because ['foo','bar','baz'] contains single-quotation marks. JSON RFC specifies that string should be enclosed in double-quotation marks.
There could be a few work-arounds.
Switch quotation marks in the data- attributes:
<tag data-sdata='["foo","bar","baz"]' />
Or replace in Javascript:
values = JSON.parse($data.sdata.replace("'","\""));
You don't need to parse. Simply use .data(), the function does it for you.
I have changed your HTML, I have swapped quotes in line data-sdata="['foo', 'bar', 'baz']" as JSON should use in double-quotation(") marks.
HTML
<div id="data" data-idata="[1,2,3]" data-sdata='["foo", "bar", "baz"]'></div>
Script
out("#out1", $("#data").data('idata'));
out("#out2", $("#data").data('sdata'));
DEMO
Ofcourse you cannot easy parse corrupted data for 100% this goes for any data-formats and not only JSON.
If the reason the data are malformed are always the same you should fix it with some str_find and replacement functions.
If it is irregular you have no real chance except writing a really intelligenz and big algorithm. The best way here would be to try to extract the real raw data out of the corrupted string and build a real JSON string with valid syntax.
Try
html
<div id="data" data-idata="[1,2,3]" data-sdata='["foo","bar","baz"]'></div>
<div id="out1">out1</div>
<div id="out2">out2</div>
js
$(function () {
var out = function (outputId, elem, dataId) {
return $.each(JSON.parse($(elem).get(0).dataset["" + dataId])
, function (index, value) {
$("<ul>").html("<li>" + index + " -> " + value + "</li>")
.appendTo(outputId);
});
};
out("#out1", "#data", "idata");
out("#out2", "#data", "sdata");
});
jsfiddle http://jsfiddle.net/guest271314/4mJBp/

How to "Quote" a String in jQuery?

Info's: I have some javascript code that i will show below, who i'm having problem with quotes.
html = [];
style = 'class=odd';
html.push('<li '+style+' onclick=SelectItem("'+ele.id+'","'+idItem+'","'+dsItem+'","'+qtItem+'"); >'+id+' - '+$iObjItensListaVenda.result.ds_item[i]+'</li>');
I have strings that i get from a JSON Object, as you see above.
Problem: But when i'm trying to place it as a Function Parameter on the onClick event of the <li> element, my resulting html <li> element becomes totally unformatted like that:
<li natural,"150");="" white="" american="" onclick="SelectItem("descItem1","2",TELHA" class="odd">00002 - TELHA AMERICAN WHITE NATURAL</li>
What do i want: i need a solution like a function, maybe already exists in jQuery, to Quote my String. Like a QuoteStr("s t r i n g"); to become ""s t r i n g"".
Maybe you're complaining about:
The variable ele is a html <input> element.
The variable idItem contains only numbers, they come from a JSON Object.
The variable dsItem its a string containing Item Description, it comes from the JSON Object too.
The variable qtItem contains only numbers, it is the quantity of the items, it comes from the JSON too.
The sane solution would be to use jQuery to build the element and bind the event handler, not building an HTML string:
var $li = $('<li />', {
"class": "odd",
on: {
click: function() {
SelectItem(ele.id, idItem, dsItem, qtItem);
}
},
text: id + ' - ' + $iObjItensListaVenda.result.ds_item[i]
});
If you are doing this in a loop and the variables end up having the wrong values, please see JavaScript closure inside loops – simple practical example. Alternative you could use jQuery's .data API to set and get those values.
Try \" instead of ' in onClick
$(".container").append("Edit");
You can use quotes in a string by escaping them with a backslash.
var text = "s t r i n g";
"\"" + text + "\"" === "\"s t r i n g\"";
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
You can always use backslash to escape quotes:
console.log('te\'st'); // te'st
console.log("te\"st"); // te"st
You can do the same thing for your string, but I'd suggest you rewrite the whole thing into something more usable. By that I mean not using strings to build objects, but building objects directly.
For example:
var li = document.createElement('li');
li.className = myClass;
li.onclick = function(){/*...*/};
It gets even easier with jQuery.

Can't get JSON properties to display via jQuery

For some reason I just can't seem to be able to display properties from this JSON string:
http://www.easports.com/iframe/fifa14proclubs/api/platforms/PS4/clubs/51694/members
I've sat here for the last 2-3 hours trying out different ways to select single properties such as the name of the first person in the array. A couple selectors I've tried:
$("#output").append(data.raw[0].176932931.name);
$("#output").append(data.raw[0][0].name);
I always get the same error. "data.raw[0] is undefined". The JSON string is valid, I'm able to output the whole string to my page using:
document.getElementById('output').innerHTML=data.toSource();
Parsing it into a JSON object gives me another error because it already is a JSON object. By using console.log(data) I'm able to view the JSON object properly in Firebug.
data is the name of the Javascript JSON object variable that is being returned from my YQL statement.
Please, if anyone could provide some examples as to how I should go about accessing the properties of the above JSON string, that would be great.
UPDATE:
Here's the callback function from my YQL statement:
function cbfunc(json)
{
if (json.query.count)
{
var data = json.query.results.json;
$("#output").append(data.raw[0]["176932931"].name);
}
You need to use bracket notation, as identifiers starting with digits are invalid
$("#output").append(data.raw[0]["176932931"].name);
as "176932931" is an integer key so you have to access like json["176932931"].
For example
data.raw[0]["176932931"].name
see fiddle here
.count isn't a property of a json object. Try this:
var something = {"raw":[{"176932931":{"name":"Shipdawg","blazeId":176932931,"clubStatus":0,"onlineStatus":0,"nucleusId":2266699357,"personaName":"Shipdawg"},"182141183":{"name":"Beks8","blazeId":182141183,"clubStatus":0,"onlineStatus":0,"nucleusId":2272736228,"personaName":"Beks8"},"219929617":{"name":"ChelseaFC_26","blazeId":219929617,"clubStatus":0,"onlineStatus":0,"nucleusId":2304510098,"personaName":"ChelseaFC_26"},"457588267":{"name":"Lazy__Rich","blazeId":457588267,"clubStatus":0,"onlineStatus":0,"nucleusId":2495578386,"personaName":"Lazy__Rich"},"517570695":{"name":"x0__andrew__0x","blazeId":517570695,"clubStatus":0,"onlineStatus":1,"nucleusId":2549150176,"personaName":"x0__andrew__0x"},"912396727":{"name":"mizz00-","blazeId":912396727,"clubStatus":0,"onlineStatus":1,"nucleusId":1000118566560,"personaName":"mizz00-"},"915144354":{"name":"MisterKanii","blazeId":915144354,"clubStatus":2,"onlineStatus":0,"nucleusId":2281969661,"personaName":"MisterKanii"}}]}
function cbfunc(json)
{
if (json.raw.length)
{
$("#output").append(json.raw["0"]["176932931"].name);
}
}
cbfunc(something);
Tell me if this works for you:
function cbfunc(json)
{
$each(json, function(key, object){
console.log(key, object);
});
var raw = query.results.json.raw;
console.log(raw );
// uncomment it if you want some extra check.
if (/*typeof data.raw !=='undefined' && */data.raw.length > 0)
{
//console.log(data.raw[0]["176932931"].name);
//$("#output").append(data.raw[0]["176932931"].name);
}
}
If this works for you there's no need to reference the object to data, simply use the object its self.
JS fiddle: http://jsfiddle.net/q8xL3/2/

Why is my .data() function returning [ instead of the first value of my array?

I want to pass an array into a jQuery data attribute on the server side and then retrieve it like so:
var stuff = $('div').data('stuff');
alert(stuff[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<div data-stuff="['a','b','c']"></div>
Why does this appear to alert '[' and not 'a' (see JSFiddle link)
JSFiddle Link: http://jsfiddle.net/ktw4v/3/
It's treating your variable as a string, the zeroth element of which is [.
This is happening because your string is not valid JSON, which should use double-quotes as a string delimiter instead of single quotes. You'll then have to use single-quotes to delimit the entire attribute value.
If you fix your quotation marks your original code works (see http://jsfiddle.net/ktw4v/12/)
<div data-stuff='["a","b","c"]'> </div>
var stuff = $('div').data('stuff');
When jQuery sees valid JSON in a data attribute it will automatically unpack it for you.
Declaring it as an attribute means that it is a string.
So stuff[0] would be equivalent to: var myString = "['a','b','c']"; alert(myString[0]);
You need to make it look like this:
<div data-stuff="a,b,c"></div>
var stuff = $('div').data('stuff').split(',');
alert(stuff[0]);
Retraction: jQuery's parsing fails because it didn't meet the rules of parseJSON.
However, I will stand behind my solution. There are aspects of the others that are less than ideal, just as this solution is less than ideal in some ways. All depends on what your paradigms are.
As others have identified the value is treated as string so it is returning "[". Please try this (aaa is the name of the div and I took out the data-stuff):
$(function(){
$.data($("#aaa")[0],"stuff",{"aa":['a','b','c']});
var stuff = $.data($("#aaa")[0],"stuff").aa;
alert(stuff[0]); //returns "a"
});
A different approach is posted at jsfiddle; var stuff = $('div').data('stuff'); stuff is a string with 0th character as '['
Well, var stuff = eval($('div').data('stuff')); should get you an array

How do I concatenate a string with a variable?

So I am trying to make a string out of a string and a passed variable(which is a number).
How do I do that?
I have something like this:
function AddBorder(id){
document.getElementById('horseThumb_'+id).className='hand positionLeft'
}
So how do I get that 'horseThumb' and an id into one string?
I tried all the various options, I also googled and besides learning that I can insert a variable in string like this getElementById("horseThumb_{$id}") <-- (didn't work for me, I don't know why) I found nothing useful. So any help would be very appreciated.
Your code is correct. Perhaps your problem is that you are not passing an ID to the AddBorder function, or that an element with that ID does not exist. Or you might be running your function before the element in question is accessible through the browser's DOM.
Since ECMAScript 2015, you can also use template literals (aka template strings):
document.getElementById(`horseThumb_${id}`).className = "hand positionLeft";
To identify the first case or determine the cause of the second case, add these as the first lines inside the function:
alert('ID number: ' + id);
alert('Return value of gEBI: ' + document.getElementById('horseThumb_' + id));
That will open pop-up windows each time the function is called, with the value of id and the return value of document.getElementById. If you get undefined for the ID number pop-up, you are not passing an argument to the function. If the ID does not exist, you would get your (incorrect?) ID number in the first pop-up but get null in the second.
The third case would happen if your web page looks like this, trying to run AddBorder while the page is still loading:
<head>
<title>My Web Page</title>
<script>
function AddBorder(id) {
...
}
AddBorder(42); // Won't work; the page hasn't completely loaded yet!
</script>
</head>
To fix this, put all the code that uses AddBorder inside an onload event handler:
// Can only have one of these per page
window.onload = function() {
...
AddBorder(42);
...
}
// Or can have any number of these on a page
function doWhatever() {
...
AddBorder(42);
...
}
if(window.addEventListener) window.addEventListener('load', doWhatever, false);
else window.attachEvent('onload', doWhatever);
In javascript the "+" operator is used to add numbers or to concatenate strings.
if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
This can happen because java script allows white spaces sometimes if a string is concatenated with a number. try removing the spaces and create a string and then pass it into getElementById.
example:
var str = 'horseThumb_'+id;
str = str.replace(/^\s+|\s+$/g,"");
function AddBorder(id){
document.getElementById(str).className='hand positionLeft'
}
It's just like you did. And I'll give you a small tip for these kind of silly things: just use the browser url box to try js syntax. for example, write this: javascript:alert("test"+5) and you have your answer.
The problem in your code is probably that this element does not exist in your document... maybe it's inside a form or something. You can test this too by writing in the url: javascript:alert(document.horseThumb_5) to check where your mistake is.
Another way to do it simpler using jquery.
sample:
function add(product_id){
// the code to add the product
//updating the div, here I just change the text inside the div.
//You can do anything with jquery, like change style, border etc.
$("#added_"+product_id).html('the product was added to list');
}
Where product_id is the javascript var and$("#added_"+product_id) is a div id concatenated with product_id, the var from function add.
Best Regards!

Categories