473,624 Members | 2,612 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

reading json object with jquery

using json like

( {"Records": [ {"firstname":"N ancy","lastname ":"Davolio" } ], "RecordCount":" 1" } )

and jquery like:

$.ajax({
....

success: function(json, status) {
if(json.Records ){alert("firstn ame= "+json.Records. firstname );}
....

I can retrieve values for firstname if I use the reference spelled out

is there a way to get it by numerical position, something like:

if(json.Records ){alert("firstn ame= "+json.Records. 0 );}

except it would work .. :)

thanks in advance
Jun 27 '08 #1
9 10863
On May 4, 8:50*pm, "Jon Paal [MSMD]" <Jon nospam Paal @ everywhere dot
comwrote:
using json like

( {"Records": [ {"firstname":"N ancy","lastname ":"Davolio" } ], "RecordCount":" 1" } )

and jquery like:

*$.ajax({
...

* * success: function(json, status) {
* * *if(json.Record s){alert("first name= "+json.Records. firstname );}
...

I can retrieve values for firstname if I use the reference spelled out

is there a way to get it by numerical position, something like:

* if(json.Records ){alert("firstn ame= "+json.Records. 0 );}

except it would work .. :)

thanks in advance
<html>
<head></head>
<body>
<script>
var jsonText, records, recordCount, i, a, b;

/*
If the data was serialized this way :
*/

jsonText='[["Nancy","Davoli o"],["Jon","Paal "]]';

records = eval(jsonText);

/*
Then you could do :
*/
recordCount = records.length;
for (i=0; i<recordCount; i++) {
a = records[i][0];
b = records[i][1]
alert( b+", "+a);
}

/*
HTH,
--Jorge.
*/
</script>
</body>
</html>
Jun 27 '08 #2
thanks,

this will work, and if I still need formal json I'll go back to hard coding names....


Jun 27 '08 #3
"Jon Paal [MSMD]" <Jon nospam Paal @ everywhere dot comwrites:
using json like

( {"Records": [ {"firstname":"N ancy","lastname ":"Davolio" } ], "RecordCount":" 1" } )

and jquery like:

$.ajax({
...

success: function(json, status) {
if(json.Records ){alert("firstn ame= "+json.Records. firstname );}
...
I hope it's "json.Recor ds[0].firstname", since Records is an array.
I can retrieve values for firstname if I use the reference spelled out

is there a way to get it by numerical position, something like:

if(json.Records ){alert("firstn ame= "+json.Records. 0 );}
json.Records[0] gives the first record.
To retrieve the "firstname" property, you need to use the "firstname"
property name. There is no ordering of named properties, so they don't
have a numerical index at all.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jun 27 '08 #4
On May 5, 5:57 am, "Jon Paal [MSMD]" <Jon nospam Paal @ everywhere dot
comwrote:
thanks,

this will work, and if I still need formal json I'll go back to hard coding names....
Cool.

It's not stated clearly enough at json.org :
http://tools.ietf.org/html/rfc4627 : line 75 :
"A JSON text is a serialized object *** or array. ***"

But what parses as valid json ?
<html>
<head>
<style>
bad {
color: red;
}
blue {
color: blue;
}
</style>
<script src="http://www.JSON.org/json2.js">
/*
Please do NOT link to json.org,
use your own copy instead.
*/
</script>

</head>
<body>
<!--567890123456789 012345678901234 567890123456789 012345678901234 567890
-->
<script>
(function () {
var testIt = function (p) {
var i, name = prefix = msg = "";
var datesAsObjects = function (key, value) {
/*
see the reviver function in the source code :
json.org/json2.js line ~104..
this is an example function that intercepts Date(mm/dd/yyyy)
and turns it into a date object instead of a string.
It's NOT part of the json standard, it's just a quick
example of a reviver function. (and it has a bug).
*/
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slic e(5, -1));
if (d) {
return d;
}
}
return value;
}
try {
data = JSON.parse(p, datesAsObjects) ;
/*
See the source : json.org/json2.js
*/
if (typeof data === 'object') {
if (data.construct or === Array) {
msg = "an object : Array : ";
for (i=0;i<data.len gth;i++) {
msg += prefix+"e["+i+"]: "+typeof data[i]+" = "+data[i];
prefix = ", ";
}
} else if (data.construct or === Object) {
msg = "an object : Object : ";
for (name in data) {
if (data.hasOwnPro perty(name)) {
msg += prefix+name+": "+typeof data[name]+" = "+data[name];
}
}
} else {
msg="an object whose constructor is : "+data.construc tor;
}
} else {
msg = "a " + typeof data + ": " + data;
}
document.write( "The string "+p+" was parsed as");
document.write( " VALID json.\nIt produced " + msg + "<br>");
} catch (e) {
document.write( "<bad>The string "+p+" is NOT");
document.write( " valid json.</bad><br>");
}
};

/*
In theory, just arrays and objects,
in practice :
let's see what's what (valid json?) :
*/

testIt('01/15/2008'); testIt('[01/15/2008]');
testIt('15/01/2008'); testIt('[15/01/2008]');
testIt('"01/15/2008"'); testIt('["01/15/2008"]');
testIt('"15/01/2008"'); testIt('["15/01/2008"]');
testIt('Date(15/01/2008)'); testIt('[Date(15/01/2008)]');
testIt('Date(01/15/2008)'); testIt('[Date(01/15/2008)]');
/*
the next one gives the date wrong.
*/
document.write( "<blue>");
testIt('"Date(1 5/01/2008)"'); testIt('["Date(15/01/2008)"]');
document.write( "</blue>");
testIt('"Date(0 1/15/2008)"'); testIt('["Date(01/15/2008)"]');
testIt('true'); testIt('[true]');
testIt('True'); testIt('[True]');
testIt('false') ; testIt('[false]');
testIt('False') ; testIt('[False]');
testIt('null'); testIt('[null]');
testIt('Null'); testIt('[Null]');
testIt('"true"' ); testIt('["true"]');
testIt('"True"' ); testIt('["True"]');
testIt('"false" '); testIt('["false"]');
testIt('"False" '); testIt('["False"]');
testIt('"null"' ); testIt('["null"]');
testIt('"Null"' ); testIt('["Null"]');
testIt('Hi there !'); testIt('[Hi there !]');
testIt('"Hi there !"'); testIt('["Hi there !"]');
testIt('99'); testIt('[99]');
testIt('99.98') ; testIt('[99.98]');
testIt('9.98e-16'); testIt('[9.98e-16]');
testIt('"99"'); testIt('["99"]');
testIt('"99.98" '); testIt('["99.98"]');
testIt('"9.98e-16"'); testIt('["9.98e-16"]');
testIt('[["Nancy","Davoli o"],["Jon","Paal "]]');
/*
the next one gives an invalid date.
*/
document.write( "<blue>");
testIt('["Date(01/15/2008)","Date()" ,"Date","99" ,99]');
document.write( "</blue>");
testIt('{"aProp erty":99}');
testIt('"functi on(){alert(wind ow.location.hre f)}"');
testIt('functio n(){alert(windo w.location.href )}');
testIt('"window .aGlobalVar=99" '); testIt('window. aGlobalVar=99') ;

/*
HTH
--Jorge.
*/
})();
</script>
</body>
</html>
Jun 27 '08 #5
The jQuery support list is here:
http://groups.google.com/group/jquery-en
Jun 27 '08 #6
On May 5, 3:07*pm, jdalton <John.David.Dal ...@gmail.comwr ote:
The jQuery support list is here:http://groups.google.com/group/jquery-en
The json support list is here:
http://tech.groups.yahoo.com/group/json/
Jun 27 '08 #7
A solution to the original json structure:

success: function(json, status) {
var records = json.Records;
var str = "";
if(records ){
for(var i = 0; i < records.length; i++){
for(var j in records[i]){
str += j + " --" + records[i][j] + "\n";
}
}
alert(str);
}

"Jon Paal [MSMD]" <Jon nospam Paal @ everywhere dot comwrote in message news:McCdnX-gdIMbmIPVnZ2dnU VZ_s-pnZ2d@palinacqu isition...
using json like

( {"Records": [ {"firstname":"N ancy","lastname ":"Davolio" } ], "RecordCount":" 1" } )

and jquery like:

$.ajax({
...

success: function(json, status) {
if(json.Records ){alert("firstn ame= "+json.Records. firstname );}
...

I can retrieve values for firstname if I use the reference spelled out

is there a way to get it by numerical position, something like:

if(json.Records ){alert("firstn ame= "+json.Records. 0 );}

except it would work .. :)

thanks in advance

Jun 27 '08 #8
On May 6, 5:27*am, "Jon Paal [MSMD]" <Jon nospam Paal @ everywhere dot
comwrote:
A solution to the original json structure:

success: function(json, status) {
* var records = json.Records;
* var str = "";
* if(records ){
* *for(var i = 0; i < records.length; i++){
* * for(var j in records[i]){
* * *str += j + " --" + records[i][j] + "\n";
* * }
* *}
* alert(str);
* }
Yep !

Still, I'd consider that :

{"Records":
[{"firstname":"N ancy","lastname ":"Davolio" }],"RecordCount": "1"}

contains as much info as :

[["Nancy","Davoli o"]]

Bus is almost 3x longer.

If you want the headers, you can save them into Records[0] (and keep
sending them but only once) :

[["firstname","la stname"],["Nancy","Davoli o"]]

Which still is more compact than the original structure :

[["firstname","la stname"],["Nancy","Davoli o"]]
{"Records":
[{"firstname":"N ancy","lastname ":"Davolio" }],"RecordCount": "1"}

and tends to be still more compact as the # of records go up : 175 vs
340 chars. (~50%)

[
["firstname","la stname"],
["Nancy","Davoli o"],
["Nancy","Davoli o"],
["Nancy","Davoli o"],
["Nancy","Davoli o"],
["Nancy","Davoli o"],
["Nancy","Davoli o"],
["Nancy","Davoli o"]
]

==

{"Records":[
{"firstname":"N ancy","lastname ":"Davolio" },
{"firstname":"N ancy","lastname ":"Davolio" },
{"firstname":"N ancy","lastname ":"Davolio" },
{"firstname":"N ancy","lastname ":"Davolio" },
{"firstname":"N ancy","lastname ":"Davolio" },
{"firstname":"N ancy","lastname ":"Davolio" },
{"firstname":"N ancy","lastname ":"Davolio" }],
"RecordCount":" 3"}

And the code is almost the same :

success: function(json, status) {
var i, j, r = json, str = "";
if (r) {
for (i=1; i<r.length; i++) {
for (j=0; j<r[i].length; j++) {
str += r[0][j] + " --" + r[i][j] + "\n";
}
}
alert (str);
}

--Jorge.
Jun 27 '08 #9
Jorge wrote:
On May 5, 3:07 pm, jdalton <John.David.Dal ...@gmail.comwr ote:
>The jQuery support list is here:http://groups.google.com/group/jquery-en

The json support list is here:
http://tech.groups.yahoo.com/group/json/
Peer reviews are included here:
http://groups.google.com/groups?q=%2...ing=d&filter=0
PointedEars
--
Prototype.js was written by people who don't know javascript for people
who don't know javascript. People who don't know javascript are not
the best source of advice on designing systems that use javascript.
-- Richard Cornford, cljs, <f8************ *******@news.de mon.co.uk>
Jun 27 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

20
6838
by: Luke Matuszewski | last post by:
Welcome As suggested i looked into JSON project and was amazed but... What about cyclical data structures - anybody was faced it in some project ? Is there any satisactional recomendation... PS i am ready to use JSON as data/object interchange when using AJAX and my J2EE project - because it is easier to traverse the JavaScript object than its XML representation (so of course may argue).
2
3742
by: Kevin Newman | last post by:
Hello, I noticed that the JavaScript library for JSON posted on json.org (http://www.json.org/json.js) is modifying Object.prototype (adding a method - toJSONString). I thought this was considered bad practice because it can disrupt the use of for in loops on Objects. Am I incorrect? Thanks,
3
10169
by: Adam | last post by:
I'm trying to retrieve some values from a json object, but instead it's giving me the property name. For example: var json = { "glossary": { "title": "example glossary" } }; console.log(json); alert(json.glossary.title); for (var x in json) { console.log(x); alert(x.title); } This will show me the json object in the console with glossary and title underneath it. When the alert for json.glossary.title fires, it
5
16121
by: Otto Wyss | last post by:
I've now been looking for a week for a simple but useful sample on how to get a list of entries (persons) via an XMLHttpRequest using Json/PHP on the server. So far I've found about a thousend different tutorials and code samples but not a single one, where the server returns an array of entries. Very few samples use Json at all and almost none show the server code. So does anybody know a sample which - uses just a small javascript...
2
3313
by: ChrisO | last post by:
I've been pretty infatuated with JSON for some time now since "discovering" it a while back. (It's been there all along in JavaScript, but it was just never "noticed" or used by most until recently -- or maybe I should just speak for myself.) The fact that JSON is more elegant goes without saying, yet I can't seem to find a way to use JSON the way I *really* want to use it: to create objects that can be instantated into multiple...
5
10570
by: Marc | last post by:
I'm aware that there are significant differences between VBScript objects and JScript objects but that doesn't mean something like the following should give me such troubles? <%@ Language=VBScript %> <script language="jscript" runat="server"> var json = {"widget":}; </script> <% Response.Write json.widget & "<br />"
23
3195
by: dhtmlkitchen | last post by:
JSON We all know what it is. In ECMAScript 4, there's a JSON proposal: Object.prototype.toJSONString String.prototype.parseJSON The current proposal, String.prototype.parseJSON, returns an object.
3
7064
by: threedot | last post by:
JSON engine of VBScript based ASP server technology, served on it's deficiency of processing speciality. Also there have been like these projects put they had some deficiencies. For instance * find result late * difficult application * don't support full UNICODE * don't compatible with primitive datatypes * don't support to multi dimensional arrays * isn't extendable and iteratable
0
2486
by: JonTwend | last post by:
I am working with the Twitter API and finding it great fun and generally easy to use. But I am having trouble getting to the data in the trends/current.json file. I am able to loop through the object data with a foreach loop and print it out. But I want to do more with the data than just print it. Just to be clear, I want to work with the daily and weekly trends but I am using the simpler current trends for this example. What I want to...
0
8246
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8631
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8341
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8490
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4184
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2612
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1796
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1489
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.