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? Commented Oct 18, 2013 at 14:31
  • possible duplicate of deserialize from json to javascript object Commented 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 Commented Oct 18, 2013 at 14:33
  • There is no such thing as a "JSON array". JSON is a string. Commented 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 Commented 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
Sign up to request clarification or add additional context in comments.

Comments

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

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.