0

I am having trouble accessing certain properties in an object that I receive as JSON from a server-side script, as the result of an AJAX call that I am making. My JSON data can come in one of two forms, depending on the data in the object itself.

Form 1:

        "MY_OBJ" : { "FILE" : "myfile.txt",
        "PARAMS" : { "PARAM" : { "KEY" : "mykey",
                "VALUE" : "myvalue"
              } }
          }

Form 2:

        "MY_OBJ" : { "FILE" : "myfile.txt",
        "PARAMS" : { "PARAM" : [ { "KEY" : "mykeyone",
                  "VALUE" : "myvalueone"
                },
                { "KEY" : "mykeytwo",
                  "VALUE" : "myvaluetwo"
                }
              ] }
          }

This is how I am currently trying to parse the data to display in the browser:

    function(v) {
var myFormattedData = v.FILE;
if (v.PARAMS !== undefined && v.PARAMS.PARAM !== undefined &&  v.PARAMS.PARAM.KEY !== undefined && v.PARAMS.PARAM.VALUE !== undefined) {
    myFormattedData += '<br />' + v.PARAMS.PARAM.KEY + ' : ' + v.PARAMS.PARAM.VALUE;
} }

This method works fine when my data is in Form 1. In that situation I will get output in the browser like...

myfile.txt
mykey : myvalue

...which is exactly what I want.

However, when the data is in Form 2 all I get is the file name displayed in the browser like this...

myfile.txt

... but what I am trying to get is something like...

myfile.txt
mykeyone : myvalueone
mykeytwo : myvaluetwo

I need to be able to handle getting the data in both forms. What's worse is that I probably also should plan for the possibility of receiving more than just one or two key-value pairs at some point in the future. I have been struggling with this for a long time. Any help is much appreciated!

Thank you!

4 Answers 4

4

To simplify processing, check the type of the PARAM object. If it is an array, then you have a response of type 2. Otherwise it's a response of type 1. Further simplify by converting type 1 to type 2 by wrapping PARAM inside an array, so you can treat everything as an array on the client side regardless of how the server sends it.

function(data) {
    var params = data.PARAMS.PARAM;
    if (!(params instanceof Array)) {
        // convert to Array to treat everything alike
        params = [ params ];
    }
    // now that we know we are always dealing with an array,
    // loop through each item and print each key, value pair
    params.forEach(function(param) {
        console.log(param.KEY + ": " + param.VALUE);
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

+1 my thoughts :) Alternative (more complicated) array detection: Object.prototype.toString.call(params) === "[object Array]"
Thanks Felix. I've seen this type of type detection used in a couple of places. Is it because of compatibility with IE?
I asked myself the same question, because I was not sure anymore why this is often used instead of instanceof Array. I googled a bit, but found only this: javascript.info/tutorial/type-detection I cannot say more at the moment, sorry.
0

Try doing something like this for the second form:

for(i=0;i<v.PARAMS.PARAM.length;i++) {
   myFormattedData += '<br />' + v.PARAMS.PARAM[i].KEY + ' : ' + v.PARAMS.PARAM[i].VALUE;
}

1 Comment

I have received great answers on this! I have tried several of them in one form or another. What I have decided to go with and what seems to work best for me right now as well as having me prepared for additional key-value pairs in the future is checking for Object.prototype.toString.call(v.PARAMS.PARAM) === "[object Array]" based on comment by @Felix Kling. When it returns true I run your (Anthony Accioly) loop. When it returns false I just run my myFormattedData += '<br />' + v.PARAMS.PARAM.KEY + ' : ' + v.PARAMS.PARAM.VALUE;. Thanks!
0

In form1, v.PARAMS.PARAM.KEY will be non-null.

In form 2, it will be null.
In this case, you need to reference your keys and values as v.PARAMS.PARAM[0].KEY and v.PARAMS.PARAM[0].VALUE , and v.PARAMS.PARAM[1].KEY

Comments

0

In the second version, v.PARAMS.PARAM is an Array. You should check that it actually is an Array, then iterate that Array. The following code would only work for form 2. If it is possible that either form should return from the server, you'll need to blend your function with what I show.

function( v )
{
    var myFormattedData = v.FILE;
    if( v.PARAMS !== undefined && v.PARAMS.PARAM !== undefined && v.PARAMS.PARAM instanceof Array )
    {
        var l = v.PARAMS.PARAM.length,
            current;
        for( var i = 0; i < l; i++ )
        {
            current = v.PARAMS.PARAM[i];
            if( current.KEY !== undefined && current.VALUE !== undefined )
            {
                myFormattedData += '<br />' + current.KEY + ' : ' + current.VALUE;
            }
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.