-1

I have below JSON text format

[
{"fields": {"Num": 34, "Univ": "TUni"}, "pk": 1, "model": "app.unbased"}, 
{"fields": {"Num": 10, "Univ": "VTU"}, "pk": 1, "model": "app.unbased"}
]

I tried to access fields value of Num of the first item using Jquery, but couldn't get it. I have already gone through other questions related to JSON but no use as this form is unusual.

I tried below in the success function

success: function (json) {
            $('#PieStats').html(json.message);
            var data_json = $.parseJSON(json.message);
            alert(typeof(json.message)); // Output : string
            alert(data_json[0][0]); // Output : Undefined
            alert(typeof (json) + ' ' + typeof (data_json));  // Output : object object
            $('.ajaxProgress').hide();
        }

I have also tried using data_json['fields'][0][0] and other possible ways - doesn't work

What am I missing ?

user3128771
  • 27
  • 1
  • 1
  • 9
  • `data_json[0].fields.Num` should do it – A. Wolff Jun 20 '15 at 17:49
  • You are missing that only the top level structure is an array. – Felix Kling Jun 20 '15 at 17:50
  • Many thanks Wolff! How to access the json when we are not sure of field name ? – user3128771 Jun 20 '15 at 17:53
  • But I don't see any key named "message" in your JSON text format. Again, you should go like: `var data_json = $.parseJSON(json);`. After that, try `console.log(data_json);` to see the data structure fetched. – Ifedi Okonkwo Jun 20 '15 at 17:55
  • @user3128771 use a loop to get all the object keys. You should start by reading provided dupe link, there is a part in answer explaining it: http://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json – A. Wolff Jun 20 '15 at 17:57

2 Answers2

0

data_json[0].fields.Num is what you are looking for. Each element in the array is an object and that is why you get undefined for data_json[0][0]

Sasikanth Bharadwaj
  • 1,457
  • 1
  • 11
  • 11
0

check this:

var jsonString = '[\
{"fields": {"Num": 34, "Univ": "TUni"}, "pk": 1, "model": "app.unbased"}, \
{"fields": {"Num": 10, "Univ": "VTU"}, "pk": 1, "model": "app.unbased"}\
]';
var dataObject = JSON.parse(jsonString);
console.log(dataObject[0].fields.Num);
J2EE
  • 16