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');
3
  • How do you determine which parameters to the pass to the function? Commented Jun 11, 2016 at 18:47
  • Note: JavaScript does not have associative arrays. Commented Jun 11, 2016 at 18:54
  • @gcampbell I'm use to associating json with associative arrays. Commented Jun 11, 2016 at 19:06

1 Answer 1

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

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.