0

Grabbing an JSON array from a query. It's not printing the keyss with in the data.

What I expect:

["0":"3675E5010E2738","1":"4114009","2":"2012-11-05","3":"Active","4":"2012-12-11"]

What I get...

["3675E5010E2738","4114009","2012-11-05","Active","2012-12-11"]

JSON is produced from PHP/JSON encode:

$array = $model->ListData();
echo json_encode($array);

I've tried loading both loadRowList(); and loadAssocList(); and neither produce the keys.

2
  • 1
    What you expect is not JSON, also what does var_dump($array); give you? Commented Dec 18, 2012 at 21:03
  • Weird as most examples I've seen as JSON have the keys associated with the data. Oh well. Guess I'll just have to use numbers. Commented Dec 18, 2012 at 21:06

3 Answers 3

2

Because that's not how JSON represents arrays

["0":"3675E5010E2738","1":"4114009","2":"2012-11-05","3":"Active","4":"2012-12-11"] is not valid JSON.

{"0":"3675E5010E2738","1":"4114009","2":"2012-11-05","3":"Active","4":"2012-12-11"} is, but that's the representation of an object, not an array.

If $model->ListData(); returns an array, as your code suggests that it does, then the representation that you're getting is correct.

Anyway, since json[0] would work the same way, regardless of whether it was an array or an object with numerical keys, what does it matter?

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

2 Comments

First time using JSON. Did not know that. Used numerical keys in PHP, got confusing after a while. I was hoping to use assoc arrays with JSON.
so, getting the data from JSON/AJAX would go like: $.ajax({ url: url, datatype: JSON, success: function(data){ $('#test').html(data.0); } });
1

You have numerical keys which are in order starting from 0. You don't need to have the keys present for it to be interpreted correctly.

Comments

0

Remember that JSON is javascript object notation, this means that it uses javascript syntax.

var myObject = { 0: 'zero', 1: 'one', 2: 'two' }; var myArray = [ 'zero', 'one', 'two' ];

Arrays and Objects are used for different purposes. Objects supports keys, arrays do not.

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.