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!