1

I have a really simple Json array and I need to get back

  • the number of items within the array.
  • the list of entries in order of the id.

The array is as follows:

{"error":false,"error_msg":"","body":
{"records":[{"name":"Application","id":1},
            {"name":"Fees Paid","id":2},
            {"name":"Evidence Verification","id":3},
            {"name":"Details QA","id":4},
            {"name":"Grade Approval","id":5},
            {"name":"Welcome Pack","id":6}]
},
"validation_errors":[]}
Sideshow
  • 1,321
  • 6
  • 28
  • 50
  • by within the array you mean within `records`? – Vandesh Oct 18 '13 at 14:31
  • possible duplicate of [deserialize from json to javascript object](http://stackoverflow.com/questions/6487167/deserialize-from-json-to-javascript-object) –  Oct 18 '13 at 14:33
  • `body.records.name.length -> I need a `foreach statement to list out the names in order of their ids. The array is returned into a function as data therefore `data.body.records.name` has also been tried – Sideshow Oct 18 '13 at 14:33
  • There is no such thing as a "JSON array". JSON is a string. – Niet the Dark Absol Oct 18 '13 at 14:34
  • You're going to need to just loop over (parsed json data).records and then do work with records[i].id and records.length – megawac Oct 18 '13 at 14:36

2 Answers2

3

Assuming you have JSON.parsed your string into a variable called jsonobj, the following statements get the data you want:

var len = jsonobj.body.records.length;
jsonobj.body.records.sort(function(a,b) {return a.id-b.id;});
// now iterate through jsonobj.body.records and they will be in ascending ID order
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

Say you have your Object held in variable jObj, clone the Array/Objects so you preserve the originals, sort it as desired then return an Array which just holds the name properties.

jObj['body']['records']
    .map(function (e) {return {'id': e['id'], 'name': e['name']};}) // clone
    .sort(function (a, b) {return +a['id'] - +b['id'];})            // sort asc
    .map(function (e) {return e['name'];});                         // get names
/* [
    "Application", "Fees Paid",      "Evidence Verification",
    "Details QA",  "Grade Approval", "Welcome Pack"
] */
Paul S.
  • 64,864
  • 9
  • 122
  • 138