PseudoPsyche
PseudoPsyche

Reputation: 4592

How to access elements of JSON array in javascript?

I'm currently creating an ArrayList in Java, then running the .toJson function from Google-gson on it:

public String statusesToJson(ArrayList<String> statuses){
    Gson gson = new Gson();
    return gson.toJson(statuses);
}

Which results in the JSON:

[ "u", "u", "u", "u" ]

Then in JSP I'm passing it into JavaScript:

<script language="JavaScript" type="text/javascript">CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', '<%=model.arrayListToJson(model.getStatuses()) %>');</script>

Then in the JavaScript I'm parsing it to a JSON array:

CheckStatus.statuses = JSON.parse(statuses);
alert(CheckStatus.statuses);

This then results in the following output:

u, u, u, u

The problem is that the following doesn't work and causes my page to not load:

alert(CheckStatus.statuses[0]);

What's wrong with this?

EDIT: Loaded Function:

loaded : function(guid, context, statuses) {
        CheckStatus.guid = guid;
        CheckStatus.context = context;
        CheckStatus.statuses = JSON.parse(statuses);
        alert(CheckStatus.statuses[0]);

        if(CheckStatus.init == null){
            submitForm('checkStatusForm', CheckStatus.guid);
            CheckStatus.init = true;
        }

        setupForm('checkStatusForm', function(){CheckStatus.validStatus();});

        //CheckStatus.setImages();

        applyCSS3('Check_Status');
    }

Valid Status Function:

validStatus : function(){
        CheckStatus.params = $('#checkStatusForm').serializeObject();

        if(document.getElementById('regionID').value != "" && document.getElementById('regionAction').value != ""){
            submitForm('checkStatusForm', CheckStatus.guid);
        }else{
            error("Cannot Commit", "You must select an action before attempting to commit.");
        }
    },

Setup Form Function:

/**
 * Sets up the form to submit when the user presses enter inside an input
 * element. Also calls the callback when the form is submitted, does not
 * actually submit the form.
 * 
 * @param id The id of the form.
 * @param callback The callback to call.
 * @return Nothing.
 */
function setupForm(id, callback) {
    $('#' + id + ' input').keydown(function(e) {
        if (e.keyCode === 13) {
            $(this).parents('form').submit();
            e.preventDefault();
        }
    });
    $('#' + id).submit(function(e) {
        e.preventDefault();
        callback();
    });
}

Submit Form Function:

/**
 * Serializes and submits a form.
 * 
 * @param id
 *            The id of the form to submit.
 * @param guid
 *            The guid of the page the form is on to pass to the server.
 * @return nothing.
 */
function submitForm(id, guid) {
    var subTabId = $('#' + id).closest('#tabs > div > div').attr(
            'id'), tabId = $('#' + id).closest('#tabs > div')
            .attr('id'), data = $('#' + id).serializeArray();
    data.push( {
        name : "framework-guid",
        value : guid
    });
    $.ajax( {
        type : 'POST',
        cache : 'false',
        url : '/pasdash-web/' + tr("_", "", tabId.toLowerCase()) + '/' + tr("_", "", subTabId)
                + '.jsp',
        data : data,
        success : function(html) {
            $('#' + subTabId).html(html);
            resourceChanged(tabId, subTabId,
                    $('#' + id + ' input[name="framework_command"]')[0].value,
                    guid);
        },
        error : function(jqXHR, textStatus, errorThrown) {
            error('Ajax Error', textStatus);
        }
    });
    return false;
}

Upvotes: 1

Views: 1402

Answers (3)

Ruan Mendes
Ruan Mendes

Reputation: 92274

You don't need to wrap your JSON with strings, that will just force you to have to reparse it. I would try removing those quotes and not calling JSON.parse

loaded : function(guid, context, statuses) {
    CheckStatus.guid = guid;
    CheckStatus.context = context;
    // Here's the change
    CheckStatus.statuses = statuses;
    alert(CheckStatus.statuses[0]);

And change your HTML to be

<script type="text/javascript">
    CheckStatus.loaded('<%=model.getPageId() %>', 
                       '<%=request.getContextPath() %>',
                       // the following line should output something like
                       // ["a", "b"]
                       // which is perfectly valid JavaScript
                       <%=model.arrayListToJson(model.getStatuses()) %>);
</script>

Upvotes: 1

JohnB
JohnB

Reputation: 13713

Check the type of the result of JSON.parse (). Seems to me that it is a string and not an array. Maybe a pair of quotes somewhere that should not be there?

Upvotes: 0

Pointy
Pointy

Reputation: 413737

You should be able to write:

CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', <%=model.arrayListToJson(model.getStatuses()) %>);

without the quotes around the last argument. Then, that "loaded()" function will get the object directly and there'll be no need to call "JSON.parse()".

Upvotes: 0

Related Questions