Link to home
Start Free TrialLog in
Avatar of Keith McElroy
Keith McElroy

asked on

JSON extract data

JSON data parse
How can  make the following code extract the numeric value from the "meals" element

Need the numeric value from this:  "meals":55. which is contained in the return json from the following getJSON

code:
       $.getJSON("https://api.gsa.gov/travel/perdiem/v2/rates/city/Richland/state/WA/year/2019?api_key=8DYKMOjODhqMfQLD3t4xFsXVeav1LkIPX5aOihPK", function (data) {
             var items = [];
            $.each( data, function( key, val ) {
                  //items.push( "<li id='" + key + "'>" + val + "</li>" );
                  //alert(key + " "+ val);
            });            

sample return json (see meals:55 below:
{"request":null,"errors":null,"rates":[{"oconusInfo":null,"rate":[{"months":{"month":[{"value":94,"number":1,"short":"Jan","long":"January"},{"value":94,"number":2,"short":"Feb","long":"February"},{"value":94,"number":3,"short":"Mar","long":"March"},{"value":94,"number":4,"short":"Apr","long":"April"},{"value":94,"number":5,"short":"May","long":"May"},{"value":94,"number":6,"short":"Jun","long":"June"},{"value":94,"number":7,"short":"Jul","long":"July"},{"value":94,"number":8,"short":"Aug","long":"August"},{"value":94,"number":9,"short":"Sep","long":"September"},{"value":94,"number":10,"short":"Oct","long":"October"},{"value":94,"number":11,"short":"Nov","long":"November"},{"value":94,"number":12,"short":"Dec","long":"December"}]},]"meals":55,"zip":null,"county":"","city":"Standard Rate","standardRate":"false"}],"state":"CA","year":2019,"isOconus":"false"}],"version":null}
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Your posted JSON was invalid.

Here is one from the link in the post

https://jsfiddle.net/mplungjan/97tvy85o/

const data = {
  "request": null,
  "errors": null,
  "rates": [{
    "oconusInfo": null,
    "rate": [{
      "months": {
        "month": [{
          "value": 97,
          "number": 1,
          "short": "Jan",
          "long": "January"
        }, ...
        }]
      },
      "meals": 66,
      "zip": null,
      "county": "Benton \/ Franklin",
      "city": "Richland \/ Pasco",
      "standardRate": "false"
    }],
    "state": "WA",
    "year": 2019,
    "isOconus": "false"
  }],
  "version": null
}
let meals = [];
data.rates.forEach(item => item.rate.forEach(item => meals.push(item.meals)));
console.log(meals + " or " + data.rates[0].rate[0].meals)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Michel Plungjan
Michel Plungjan
Flag of Denmark image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Keith McElroy
Keith McElroy

ASKER

This worked directly and really helps me move forward learning, using json.
I truly appreciate your expertise on this.
You are welcome!