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":[]}
5
  • by within the array you mean within records?
    – Vandesh
    Oct 18, 2013 at 14:31
  • possible duplicate of deserialize from json to javascript object
    – user1047100
    Oct 18, 2013 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, 2013 at 14:33
  • There is no such thing as a "JSON array". JSON is a string. Oct 18, 2013 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, 2013 at 14:36

2 Answers 2

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
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"
] */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.