Home > Software design >  How to filter JSON response by list
How to filter JSON response by list

Time:05-13

I'm trying to filter JSON response by list. Basically I'm passing a list of product ID's in the contains method and fetch the result accordingly but unable to do it

here is my code

  List productID = ['2354', '5831'];

  Future getData() async {
    var response = await http.get(Uri.parse(jsonURL));
    var decodeResponse = jsonDecode(response.body);
    List data = decodeResponse['items']; // JSON Response
    List filteredData = data.where((element) => productID.any((result) => element['_id'].contains(result))).toList(); // returns nothing

    return filteredData;
  }

JSON RESPONSE

{
  "items": [
    {
      "subtitle": "<ul class=\"font_8\">\n  <li><p class=\"font_8\">Crib is the ideal baby furniture for your nursery needs. That is why we have designed this 4-in-1 cribs (baby bedside sleeper, portable playard, playpens for babies, swing mode). Multi-mode, lightweight and easy to carry, you can use this baby bassinet in the bedroom, living room, or while you are on the go. Simply fold it, pack in your travel bag and get ready to go!</p></li>\n  <li><p class=\"font_8\">Multi-purpose baby furniture-use our multi-purpose bedside sleeper for all-weather care. Our cribs have good air circulation, with double-layer mesh wall panels and detachable sides, which are easy to pick and place when you need to feed or change babies. With the baby by your side, you can relax and get the rest you need.</p></li>\n  <li><p class=\"font_8\">4 levels of height adjustment-from the baby room to the living room, our bedside cribs can be adjusted to 4 different heights to make sleep and breastfeeding easy. It can be easily slid into place and locked securely, so the baby can always be safely by your side.</p></li>\n  <li><p class=\"font_8\">Two sides mesh windows allow visibility and ventilation for the baby, giving baby a cooler and comfortable space to rest. Easy to attach or remove from parents’ bed using the two safe fastening straps provided. The horizontal foot bar and the mattress support frame provide better stability and safety.</p></li>\n  <li><p class=\"font_8\">FOR BABY NEWBORNS UP TO 36 MONTHS – our bedside sleeper is the ideal baby furniture to meet the needs of nurseries. Our bedside toilets have a strong and sturdy steel frame and comfortable and wide base, which are easy to assemble and comply with all consumer product safety regulations.meet ASTM F2906 safety standards, CE, CPSC certified.</p></li>\n</ul>",
      "image": "wix:image://v1/1d3480_b5ef483b393146ca877c7aa0baf50e57~mv2.jpg/81jOo9cKTaL._AC_SX679_.jpg#originWidth=679&originHeight=744",
      "_id": "6cadd029-87dc-433d-b186-2f8b72782ccc",
      "_owner": "1d3480e5-0eda-47ef-8406-38d89bf15ded",
      "_createdDate": "2022-05-11T02:00:02.512Z",
      "discountedPrice": "$110.99",
      "_updatedDate": "2022-05-11T02:00:02.512Z",
      "getDealLink": "https://amzn.to/3l16zCy",
      "brands": [
        "Amazon"
      ],
      "originalPrice": "$149.99",
      "title": "Adjustable Portable Travel Baby Crib With Carrying Bag ",
      "amazonlogo": "wix:image://v1/1d3480_ffad681242174f799ddea471e649ef7b~mv2.png/amazon_PNG24.png#originWidth=1024&originHeight=346",
      "save": "SAVE 40%",
      "link-items-all": "/items/",
      "link-items-title": "/items/adjustable-portable-travel-baby-crib-with-carrying-bag-"
    },
    {
      "subtitle": "<ul class=\"font_8\">\n  <li><p class=\"font_8\">65% Polyester, 35% Cotton</p></li>\n  <li><p class=\"font_8\">Imported</p></li>\n  <li><p class=\"font_8\">Button closure</p></li>\n  <li><p class=\"font_8\">Machine Wash</p></li>\n  <li><p class=\"font_8\">Either tagless or with easily removed tearaway tag for comfort</p></li>\n  <li><p class=\"font_8\">FreshIQ advanced odor protection technology helps keep you fresh</p></li>\n  <li><p class=\"font_8\">X-Temp technology is designed to adapt to your body temperature and activity to keep you cool and dry for all day comfort</p></li>\n</ul>\n<p class=\"font_8\">Show lessMid-weight fabric feels super-soft next to your skin<br>\nfor itch-free comfort<br>\nClassic details include ribbed stay-flat collar and tailored 3-button placket<br>\nEither or with easily removed tearaway tag for comfort<br>\n</p>",
      "_id": "2354",
      "_owner": "1d3480e5-0eda-47ef-8406-38d89bf15ded",
      "_createdDate": "2022-05-10T19:25:56.073Z",
      "discountedPrice": "$13.08",
      "_updatedDate": "2022-05-10T19:25:56.073Z",
      "getDealLink": "https://amzn.to/3M4ZAnI",
      "brands": [
        "Amazon"
      ],
      "originalPrice": "$24.00",
      "title": "Hanes Men's Short Sleeve  Polo Shirts"
    },

CodePudding user response:

The error might be in this part: element['_id'].contains(result).
It should be element['_id'] == result.

CodePudding user response:

Try this code:

  List productID = ['2354', '5831'];

  Future getData() async {
    var response = await http.get(Uri.parse(jsonURL));
    var decodeResponse = jsonDecode(response.body);
    List data = decodeResponse['items']; // JSON Response
    var filteredData = [];
    for(var id in productID){
     data.forEach((element) {
       if(element["_id"].contains(id)){
         filteredData.add(element)
       }
     });
    }

    return filteredData;
  }
  • Related