Im looking for a simple script to convert JSON objects to Javascript objects, specifically being able to make an ajax call in jQuery and then convert all of the JSON that comes back into Javascript objects for me.
I've used the mapping plugin in KnockOut.js: https://github.com/SteveSanderson/knockout.mapping/tree/master/build/output
Which nicely takes my JSON result and creates the relevant objects in knockout.
Anything currently exist to do this without knockout?
jquery automatically does this for you.
from the JQuery documentation for getJSON:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
Just specify the dataType setting as 'json' in the $.ajax call, or use the $.getJSON method, and the JSON result will automatically be parsed into a Javascript object.
I'm guessing here, but if you want to convert them into already defined javascript objects you need the second argument in the JSON.parse function. Check MDN's documentation https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse.
Very simple example.
JSON.parse(json,function(prop,val){
if(prop==='objName'){
new myObj(val);
}
});
For use in JQUERY: http://api.jquery.com/jQuery.parseJSON/
For use in simple JS: https://github.com/douglascrockford/JSON-js (look at json.js or json2.js)
Knowing that it's well-formed:
var myObject = eval('(' + myJSONtext + ')');
Related
I do an ajax call to a script that returns data. I see the data in firebug and it is correct. When the data comes back I do a sort and it works too. I see in firebug the object is sorted the way I want. After the sort I try to access a key/value pair. I see in firebug that the key/value I want is in the object. When I try to use the object key/value to assign to a var it is undefined. I'm trying to aggregate repeating data. If I'm not using the best way to do it, please help me with a better method.
data sample
coreDate "060115"
coreType "asterisk_11"
fileName "/var/www/html/Cores/gdb.hamid.asterisk.060115"
jid "hamid"
code
$.when (
$.ajax( {
type:"GET",
url: 'cf.php',
dataType: 'json',
timeout: 120000,
})
)
.done(function(coreInfo) {
coreInfo.sort(function(a,b) { return a.coreType > b.coreType } );
var coreStats={};
coreStats.numOfCores=0;
coreStats.numOfCoreType=0;
coreStats.prevCoreType=coreInfo.coreType;
// for some reason coreInfo.coreType is not defined. The coreInfo object exists and coreType is there. I tried this.coreType but is undefined.
$.each(coreInfo, function() {
coreStats.numOfCores++;
if (coreStats.prevCoreType != this.coreType) {
// This works. why do I have to access this.coreType instead of coreInfo.coreType?
$('#list > tbody:last-child').append('<tr><td><a href="'+this.fileName+'">'+this.coreType+'</td><td>'+coreStats.numOfCoreType+'<br>core</td><td>jid</td></tr>');
coreStats.numOfCoreType=0;
}
coreStats.numOfCoreType++;
coreStats.prevCoreType=this.coreType;
// setting prevCoreType works here
});
$('#cores').html("<h1>"+coreStats.numOfCores+"</h1><br>Core Files");
})
.fail(function() {
});
From your code and description, it sounds like coreInfo is an array of objects, is that right? If it were an object, it wouldn't have a sort() method and your code would stop right there.
If it's an array, it doesn't have a property like coreInfo.coreType. Each element of the array is an object with coreType and other properties. That's why you are able to access this.coreType inside the $.each() callback. $.each() iterates through the array, element by element, and passes each individual element into the callback.
Where it looks like you're seeing coreInfo.coreType in Firebug outside the $.each(), I suspect that what you're actually seeing is coreInfo[0].coreType, i.e. the first element of the array.
To help keep track of whether a variable is an array or not I strongly suggest giving arrays names that reflect this fact: either a plural word, or add List or Array to the name, or something. A name like coreInfo sounds like a singular item. I would call the array coreList, coreArray, or simply cores. Personally I like plural words for brevity: cores for the array of core info, core for an individual element in that array.
This way when you see cores.coreType or coreList.coreType or coreArray.coreType it will look wrong.
BTW for much more readable code, I suggest never using this in a $.each() callback. Instead, use named parameters.
$.each( coreInfo, function( i, core ) {
coreStats.numOfCores++;
if( coreStats.prevCoreType != core.coreType ) {
$('#list > tbody:last-child').append(
'<tr>' +
'<td>' +
'<a href="' + core.fileName + '">' +
core.coreType +
'</a>' + // MISSING IN ORIGINAL
'</td>' +
'<td>' +
coreStats.numOfCoreType +
'<br>core' +
'</td>' +
'<td>' +
'jid' +
'</td>' +
'</tr>'
);
coreStats.numOfCoreType = 0;
}
coreStats.numOfCoreType++;
coreStats.prevCoreType = this.coreType;
});
Note that there was a missing </a> in your markup in the code above. It's much easier to spot an error like this if you indent the markup strings in the same way that you might indent raw HTML code, instead of cramming it all onto one line.
A minor point: You don't need to wrap $.ajax() inside $.when(). $.ajax() returns a Promise that you can use directly.
You don't need the code that computes coreStats.numOfCores. You can simply use the length property of the array. If you follow my suggestion to call the array cores you could do this:
$('#cores').html( "<h1>" + cores.length + "</h1><br>Core Files" );
Finally, your sort callback function has a bug and will not sort the array properly. It may have worked in a simple test case, but it will fail to sort other arrays. It has to handle all three cases: <, ==, and > and return an appropriate value for each case, perhaps like this:
coreInfo.sort( function( a, b ) {
return(
a.coreType < b.coreType ? -1 :
a.coreType > b.coreType ? 1 :
0
);
});
To verify my assumptions, can you post an example of your actual JSON data, not a formatted table?
I am returning SQL Query result as a JSONArray to a JSP page. Now i want to show the data. I have written a code but it is working fine only for 23 objects in the JSONArray if JSONArray contains more the 23 object eval or JSON.parse function doesn't work. Please let me know how to solve this problem.
Below is the JS code i have written to iterate over this JSONArray.
var data = '<%=(JSONArray) request.getAttribute("resultArray")%>';
data = eval("(" + data + ")");
$(document).ready(function() {
var table = $('<table/>').appendTo($('#column'));
var rows = $('<tr/>').appendTo(table);
$.each(data, function(rowid, row) {
var rows = $('<tr/>').appendTo(table);
$.each(row, function(column, data) {
($('<td/>').text(data)).appendTo(rows);
})});
});
Just don't let JSP print it as a JS string syntax within quotes (which obviously needs to be parsed in order to get a JS object). Get rid of those quotes. JSON is already in proper JS object syntax. That's also all what "JSON" stands for.
var data = <%=request.getAttribute("resultArray")%>;
$(document).ready(function() {
// ...
});
By the way, using scriptlets in JSP is a poor practice. If you're on JSP 2.0 already (which is out for almost a decade already), just use EL.
var data = ${resultArray};
$(document).ready(function() {
// ...
});
Note, also here, just don't quote it. It becomes otherwise a JS string instead of a JS object.
Unrelated to the concrete problem, is it absolutely necessary to introduce the extra JSON/jQuery step here? Why don't you just use for example JSTL to let JSP generate the desired HTML in the server side instead of JS/jQuery in the client side?
I am not quite adept in maneuvering jQuery, and it came to a point that I need to debug a program that was passed down from me without a documentation.
I have this var a, an object, that I really want to know the content of its collection. In my mind I need a function like foreach() in PHP to iterate over this object variable. Upon researching I end up in using jQuery.each(). Now I can clearly iterate and see what was inside var a.
However, it was kind of annoying to alert once every value on the var a. What I wanna know if it's possible to display all the contents in just one pop of alert box?
Here is my code:
$.each(a, function(index, value) {
alert(index + ': ' + value);
});
The var a contains infos such as:
creationdate: date_here
id: SWFUpload
modificationdate: date_here
type: .jpg
index: 0
name: uploaded_filename.jpg
size: size_in_bytes
BTW: The var a is called via file upload script.
Why don't you just accumulate the values in an array, then display the whole array (for instance, using JSON)? Example:
var acc = []
$.each(a, function(index, value) {
acc.push(index + ': ' + value);
});
alert(JSON.stringify(acc));
In any case, I'd suggest using a debug tool like Firebug. So you could just use console.log(a) and be able to navigate freely through the objects's fields.
In firefox you could try:
alert(yourObject.toSource());
OR you could use some plugin:
See: jQuery Dump Plugin
There seems to be a few questions around this, but I can't seem to find a conclusive answer.
I've created a WCF JSON web service that returns perfect JSON and this has been clarified using jsonlint.com. The web service returns an array (List< myresults>) and this seems to format the JSON with square brackets, like so:
[{"Image":"http://www.mywebsite/myimage.jpg"}]
Parsing the JSON on the iPhone platform seems to handle the backslashes fine, but it does not play nice with the square brackets - I had to manually remove these using this:
[str stringByReplacingOccurrencesOfString:#"[" withString:#""]; //(for each bracket)
However, I would also like to consume the same JSON in an HTML webpage using jquery and it seems I am faced with the same issue. Surely there is a more appropriate way to deal with these annoying square brackets?
I'd really appreciate if someone could post an easy way to handle the brackets - either removing them from the web service, or in my javascript code.
Thanks!
If it helps, my Javascript is as follows:
$.getJSON(urlToMyWebService, function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
The square brackets just indicate an array. As you noted, since you're returning an array, it'll have the square brackets.
You'll need to have an array on the JavaScript/Objective C side as well, that's all.
First things first ids in HTML cannot start with numbers, so using key as id for your li is invalid. Second your JSON list contains objects with Image property so you probably want this:
$.each(data, function(key, val) {
items.push('<li id="li_' + key + '">' + val.Image + '</li>');
});
and here's a live demo.
I have a JavaScript array that, among others, contains a URL. If I try to simply put the URL in the page (the array is in a project involving the Yahoo! Maps API) it shows the URL as it should be.
But if I try to do a redirect or simply do an 'alert' on the link array element I get:
function(){return JSON.encode(this);}
As far as I see it this is because the browser does an JSON.encode when it renders the page, thus the link is displayed OK. I have tried several methods to make it redirect (that's what I want to do with the link) correctly (including the usage of 'eval') but with no luck.
After following some suggestions I've run eval('(' + jsonObject + ')') but it still returns the same output.
So how's this done ?
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
See the jQuery API.
Suppose you have an array in PHP as $iniData with 5 fields. If using ajax -
echo json_encode($iniData);
In Javascript, use the following :
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "ajaxCalls.php",
data: "dataType=ini",
success: function(msg)
{
var x = eval('(' + msg + ')');
$('#allowed').html(x.allowed); // these are the fields which you can now easily access..
$('#completed').html(x.completed);
$('#running').html(x.running);
$('#expired').html(x.expired);
$('#balance').html(x.balance);
}
});
});
</script>
If you get this text in an alert:
function(){return JSON.encode(this);}
when you try alert(myArray[i]), then there are a few possibilities:
myArray[i] is a function (most likely)
myArray[i] is the literal string "function(){return JSON.encode(this);}"
myArray[i] has a .toString() method that returns that function or that string. This is the least likely of the three.
The simplest way to tell would be to check typeof(myArray[i]).
eval('(' + jsonObject + ')')
JSON decoding in JavaScript is simply an eval() if you trust the string or the more safe code you can find on http://json.org if you don't.
You will then have a JavaScript datastructure that you can traverse for the data you need.
If the object element you get is a function, you can try this:
var url = myArray[i]();
I decode JSON this way:
eval( 'var from_json_object = ' + my_json_str + ';' );