1

I have a php file wich searches in a DB, then builds and array with results and it ends and shows the result like this:

{"1":"1","2":"2","15":"15","25":"25"}

That means in position 0 there is no result, position 1 has value 1, and so on. (as far as I /know this result is a valid json output)

In jquery side I have this

     $.ajax({
        type: 'POST',
        url: 'diahoracierre.php',
        dataType: 'json',
        cache: false,
        success: function(result) {
            alert(result);
        },
    });

What I need is to "parse" result to an array and be able to play which the content using index of array, like

alert(result[X]);

on result[1] it shows 1, any other attempt shows undefined and there are at least 4 results.

3
  • Well other than the fact that your JSON is named result and not myArray, I have no idea why this isn't working Commented Feb 22, 2014 at 19:15
  • editted, having other "issues" :/ Commented Feb 22, 2014 at 19:36
  • So like this? Commented Feb 22, 2014 at 19:40

2 Answers 2

1

You have two options either you loop through result and create an array by yourself(a tedious task) or you access elements like below, please note quotes around index is required as here though we are saying index but in reality we are looking for key name.

result["index"]

e.g.

result["5"]

Also I tried your jsFiddle and it worked:

var json = '{"0":"-1","1":"1","2":"2","15":"15","3":"-1","25":"25","4":"-1","5":"-1","6":"-1","7":"-1","8":"-","9":"-1","10":"-1","11":"-1","12":"-1","13":"-1","14":"-1","16":"-1","17":"-1","18":"-1","19":"-1","20":"-1","21":"-1","22":"-1","23":"-1","24":"-1","26":"-1"}';
json = JSON.parse(json);
alert(json["25"]);
Sign up to request clarification or add additional context in comments.

Comments

1

Since you've used dataType: 'json'. Then it's no longer require you to parse the json result.

Also note that your parameter is named result in success function.So you can use:

alert(result[1]);

instead of:

alert(myArray[1]);

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.