1

I have a JSON response like this:

{"error":true,"variable":{"v_f1_email":["error-mail","mail"]}}

I am trying to access 'error-mail' and 'mail' like this:

var JSD = JSON.parse(data);

if (JSD.error == true) {
    $(JSD.variable).each(function(index, el) {
        var error = el[0];
        var type = el[0];
        console.log(error + type);
    })

Unfortunately the vars error and type are returning undefined. Where am I wrong? Thanks

4
  • aren't you supposed to go one level deeper, i.e. first get to v_f1_email...? Commented Oct 17, 2014 at 17:17
  • 1
    If you only have one then var errormsg = JSD.variable.v_f1_email; console.log(errormsg[0],errormsg[1]) Commented Oct 17, 2014 at 17:17
  • Why are you setting error and type to the same element? Commented Oct 17, 2014 at 17:18
  • You are using the wrong each method. jQuery has two: one is for jQuery objects, the other is for arrays/objects. Commented Oct 17, 2014 at 17:40

1 Answer 1

2

I believe you are looking for this:

Note: I renamed the vars in the each to show it is not an indexed array but key/value

// var JSD = JSON.parse(data); // version to use in your page
var JSD = {"error":true,"variable":{"v_f1_email":["error-mail","mail"]}};
if (JSD.error) {
   $.each(JSD.variable,function(fieldName,errorArr) {
     $("#error").append(fieldName+": error:"+errorArr[0]+", type:"+errorArr[1]); 
   });   
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="error"></div>

Sign up to request clarification or add additional context in comments.

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.