I have a json response I'm getting from a server with different response structures.
One uses another value "data" to store a link:
and the other doesn't (with "image" being the link):
I was wondering if there was a way I can get the "data.link" from the associative array with a reusable method, with linkVariableName being the key of the associative array.
function addLink(responseText, successVariableName, isError, linkVariableName)
{
var jsonResponse = JSON.parse(responseText);
var state;
if (isError)
state = !jsonResponse[successVariableName];
else
state = jsonResponse[successVariableName];
if (state) {
var link = jsonResponse[linkVariableName];
insertAtCursor(textArea, '[img]' + link + '[/img]\r\n');
} else
console.log('Error: ' + responseText);
}
so I can use either
addLink(response.responseText, 'success', false, 'data.link');
or
addLink(response.responseText, 'error', true, 'image');
-
How do you determine which parameters to the pass to the function?Felix Kling– Felix Kling2016年06月11日 18:47:08 +00:00Commented Jun 11, 2016 at 18:47
-
Note: JavaScript does not have associative arrays.gcampbell– gcampbell2016年06月11日 18:54:09 +00:00Commented Jun 11, 2016 at 18:54
-
@gcampbell I'm use to associating json with associative arrays.Mr. Trvp– Mr. Trvp2016年06月11日 19:06:03 +00:00Commented Jun 11, 2016 at 19:06
1 Answer 1
Yes you can, as explained here: Accessing nested JavaScript objects with string key
However, IMO the function tries to do too much. Why does it need to parse the JSON and extract the value? You could just pass the value directly to it:
function addLink(link) {
insertAtCursor(textArea, '[img]' + link + '[/img]\r\n');
}
And move the other logic to where you handle the response:
var isError = ...;
var response = JSON.parse(responseText);
if (isError && !response.error) {
addLink(response.image);
} else if(!isError && response.success) {
addLink(response.data.link);
} else {
console.log('Error: ' + responseText);
}