0

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');
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Mr. Trvp
  • 17
  • 4

1 Answers1

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);
}
Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • http://i.imgur.com/CxeKSpZ.gif It's quite cluttered as it is.. I figured putting everything in that method would make it a little more clear. Thank you for your solution. – Mr. Trvp Jun 11 '16 at 18:57