473,562 Members | 2,604 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

JSON/Array Question

Let's say I have the following JSON string returned from a server-side
process:

{ values: [{"name": "value1", "value": "1"},{"name ": "value2",
"value": "0"},{"name ": "operand", "value": "/"},{"name": "result",
"value": "NaN"},{"na me": "error", "value": "Divide by 0"}] }

I then create a JSON object from it using eval() (tell me if this is
not what should be done).

My question is this...how do I determine (without going through every
single record) if there is a name=error in the values array?

Here's what I do now, it can't be optimum:

var object = eval('{ values: [{"name": "value1", "value": "1"},
{"name": "value2", "value": "0"},{"name ": "operand", "value": "/"},
{"name": "result", "value": "NaN"},{"na me": "error", "value": "Divide
by 0"}] }');

for (var i = 0; i < object.values.l ength; i++) {
if (object.values[i].name == 'error') {
//do stuff...
}
}

I thought I'd try object.values.n ame['error'] of course that didn't
work...

Any help would be appreciated.

Mar 6 '07 #1
5 34388
Tom Cole wrote:
Let's say I have the following JSON string returned from a server-side
process:

{ values: [{"name": "value1", "value": "1"},{"name ": "value2",
"value": "0"},{"name ": "operand", "value": "/"},{"name": "result",
"value": "NaN"},{"na me": "error", "value": "Divide by 0"}] }

I then create a JSON object from it using eval() (tell me if this is
not what should be done).

My question is this...how do I determine (without going through every
single record) if there is a name=error in the values array?

Here's what I do now, it can't be optimum:

var object = eval('{ values: [{"name": "value1", "value": "1"},
{"name": "value2", "value": "0"},{"name ": "operand", "value": "/"},
{"name": "result", "value": "NaN"},{"na me": "error", "value": "Divide
by 0"}] }');

for (var i = 0; i < object.values.l ength; i++) {
if (object.values[i].name == 'error') {
//do stuff...
}
}

I thought I'd try object.values.n ame['error'] of course that didn't
work...

Any help would be appreciated.
Use a magical instant search algorithm.

Or, come up with a better way of returning your data :-D

In all likelyhood, it takes a negligible amount of time to go through
the whole array, unless there are a lot of entries. But it looks to me
like this might be better suited as an object, just from the example you
gave. If there are duplicate "name"s, then I'm wrong, but how about:

{
value1: 1,
value2: 0,
operand: '/',
result: 'NaN',
error: 'Divide by 0'
)

using an object instead of an array of objects that is basically a flat
object in a poorly organized table. Then you could just do

if(typeof(objec t.error) != "undefined" )
//blah blah

Or something like that.

Jeremy
Mar 7 '07 #2
On Mar 7, 7:48 am, "Tom Cole" <tco...@gmail.c omwrote:
Let's say I have the following JSON string returned from a server-side
process:

{ values: [{"name": "value1", "value": "1"},{"name ": "value2",
"value": "0"},{"name ": "operand", "value": "/"},{"name": "result",
"value": "NaN"},{"na me": "error", "value": "Divide by 0"}] }

I then create a JSON object from it using eval() (tell me if this is
not what should be done).

My question is this...how do I determine (without going through every
single record) if there is a name=error in the values array?
Your object has a single property whose value is an array of objects -
so your response object is essentially an array. You need to loop
over all the elements of the array to get the 'name' property of the
objects, there is no other way.

You might consider:

- a different data format
- include an index object to help with searching (say
an array of the indices where name='error')
- sort before sending so objects with name='error' are
first (or last and search backwards) so you can stop
when your search finds the first non-error object.

The above may not provide much practical benefit if the array isn't
large (say less than 1,000 elements).

Here's what I do now, it can't be optimum:

var object = eval('{ values: [{"name": "value1", "value": "1"},
{"name": "value2", "value": "0"},{"name ": "operand", "value": "/"},
{"name": "result", "value": "NaN"},{"na me": "error", "value": "Divide
by 0"}] }');

for (var i = 0; i < object.values.l ength; i++) {
if (object.values[i].name == 'error') {
//do stuff...
}
You could optimise that somewhat with:

var o = object.values;
var i = o.length;
do {
if (o[--i].name == 'error') {
// do stuff with o[i]
}
} while(i)

No promises though. :-)
--
Rob

Mar 7 '07 #3
Tom Cole <tc****@gmail.c omwrote:
for (var i = 0; i < object.values.l ength; i++) {
if (object.values[i].name == 'error') {
//do stuff...
}
}

I thought I'd try object.values.n ame['error'] of course that didn't
work...
strange, it is correct, did you try :

if((object.valu es[i]).name === 'error)...

parenthesing object.values[i] ?

but, as suggested by other, u might change your object structure to
object of object rather than object of array.
--
Une Bévue
Mar 7 '07 #4
On Mar 6, 8:56 pm, Jeremy <jer...@pinacol .comwrote:
Tom Cole wrote:
Let's say I have the following JSON string returned from a server-side
process:
{ values: [{"name": "value1", "value": "1"},{"name ": "value2",
"value": "0"},{"name ": "operand", "value": "/"},{"name": "result",
"value": "NaN"},{"na me": "error", "value": "Divide by 0"}] }
I then create a JSON object from it using eval() (tell me if this is
not what should be done).
My question is this...how do I determine (without going through every
single record) if there is a name=error in the values array?
Here's what I do now, it can't be optimum:
var object = eval('{ values: [{"name": "value1", "value": "1"},
{"name": "value2", "value": "0"},{"name ": "operand", "value": "/"},
{"name": "result", "value": "NaN"},{"na me": "error", "value": "Divide
by 0"}] }');
for (var i = 0; i < object.values.l ength; i++) {
if (object.values[i].name == 'error') {
//do stuff...
}
}
I thought I'd try object.values.n ame['error'] of course that didn't
work...
Any help would be appreciated.

Use a magical instant search algorithm.

Or, come up with a better way of returning your data :-D

In all likelyhood, it takes a negligible amount of time to go through
the whole array, unless there are a lot of entries. But it looks to me
like this might be better suited as an object, just from the example you
gave. If there are duplicate "name"s, then I'm wrong, but how about:

{
value1: 1,
value2: 0,
operand: '/',
result: 'NaN',
error: 'Divide by 0'
)

using an object instead of an array of objects that is basically a flat
object in a poorly organized table. Then you could just do

if(typeof(objec t.error) != "undefined" )
//blah blah

Or something like that.

Jeremy- Hide quoted text -

- Show quoted text -
I would love to do that, but what I'm writing is a method to
automatically populate a form with the "values" and I need a way to
randomly access them. Something like:

for (var i = 0; i < object.values.l ength; i++) {
var element = document.getEle mentById(object .values[i].name);
if (element) {
//this is just an example...
element.value = object.values[i].value;
}
}

For this application, my data structure works well (for me). There is
just a unique situation where I'm looking for the absence of a "name"
that I was hoping for a shortcut.

Thanks for your assistance. I'm just starting with JSON and am only
working with it in my spare time.

Mar 7 '07 #5
Tom Cole wrote:
>
I would love to do that, but what I'm writing is a method to
automatically populate a form with the "values" and I need a way to
randomly access them. Something like:

for (var i = 0; i < object.values.l ength; i++) {
var element = document.getEle mentById(object .values[i].name);
if (element) {
//this is just an example...
element.value = object.values[i].value;
}
}

<snip>

I still think you should use an object. You basically have name-value
pairs that you are returning, where the name is unique, and must conform
to HTML identifier standards (because you are also using the name as an
HTML form element name). This is perfect for an object. Instead you
are using an array of name-value pair objects, which makes no sense.

From your last post, I gather that you are doing this because you think
this is the only way you can loop through the names/values, and have
access to both the name and value as strings. This is not the case:

[Example]

var object = {
value1: 1,
value2: 0,
operand: '/',
result: 'NaN',
error: 'Divide by 0'
};

var myform = document.getEle mentById("MyFor m");
// or document.forms["MyForm"] if you prefer using name instead of id

for(var name in object)
{
//alerts, for example, "value1: 0"
alert(name + ": " + object[name]);

//sets form value to value from object
if(typeof(myfor m.elements[name]) != "undefined" )
myform.elements[name].value = object[name];

}

[/Example]

In this example, if you have a form with elements named "value1",
"value2", "operand", and "result", for example, then those form elements
will be repopulated with the values from the returned object.

Give it some thought :-)

Jeremy

Mar 7 '07 #6

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

Similar topics

20
6819
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...
2
3738
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,
1
1644
by: kungfumike | last post by:
Currently having a problem getting JSON to include properly. I When I attempt to call .toJSONstring on an array it was giving me an error. So I resorted to just alerting the array out to the screen and here is what prints out: key is: tmp1, value is: tmp1; key is: tmp2, value is: tmp2; key is: tmp3, value is: tmp3; key is: toJSONstring,...
4
2808
RMWChaos
by: RMWChaos | last post by:
The next episode in the continuing saga of trying to develop a modular, automated DOM create and remove script asks the question, "Where should I put this code?" Alright, here's the story: with a great deal of help from gits, I've developed a DOM creation and deletion script, which can be used in multiple applications. You simply feed the...
4
8860
by: im12345 | last post by:
I have the following question: Im doing a sample application using dojo and json. I have 2 classes: 1. Book class package com.esolaria.dojoex; import org.json.JSONObject; import org.json.JSONException;
5
8160
by: Jeff | last post by:
Lets say we have what I would call a "hash": var HASH =new Array(); HASH='first'; HASH='second'; HASH='third'; I'd like to return that as JSON data. Is there a direct way to do that?
7
3039
by: Logos | last post by:
I am using PHP with the JSON extension function json_decode. I have a JSON with a member named "1" (ie) { "1":"somedata" } Trying to access this via the -operator doesn't work, nor does . Putting the JSON into a foreach loop DOES access the member: foreach($json as $key=>$value) {
9
10856
by: Jon Paal [MSMD] | last post by:
using json like ( {"Records": , "RecordCount":"1" } ) and jquery like: $.ajax({ .... success: function(json, status) {
0
5366
by: crocodilu2008 | last post by:
JSON vs. XML JSON and XML are basically used for the same purpose—to represent and interchange data. I'll try to show you why you might want to use JSON rather than XML in an AJAX context by showing you an example of how an data class (actually, a list of PHP documentation pages) might be represented, first in XML. and then in JSON. This...
0
7658
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...
0
7579
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7630
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...
0
7940
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...
0
5198
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...
0
3609
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2075
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
1192
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
907
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...

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.