How to merge two JSON response into one in a Structure In Flutter

631 views Asked by At

This response is from one API call. JSON Response 1:

{
"message": "success",
"data": [
    {
        "storeid": "91",
        "productid": "37",
        "cartitemid": 48,
        "product_quantity": 8
    },
    {
        "storeid": "86",
        "productid": "74",
        "cartitemid": 52,
        "product_quantity": 1
    },
    {
        "storeid": "86",
        "productid": "73",
        "cartitemid": 51,
        "product_quantity": 6
    },
    {
        "storeid": "86",
        "productid": "76",
        "cartitemid": 50,
        "product_quantity": 1
    }
]
}

This is 2nd API call.

JSON Response 2:

{
"data": [
    {
        "storeid": 91,
        "productid": 37,
        "product_name": "hhh"
    },
    {
        "storeid": 86,
        "productid": 73,
        "product_name": "dfsdfsd"
    },
    {
        "storeid": 86,
        "productid": 76,
        "product_name": "dfsdfsd"
    }
]
}

I need this output because I need to parse this json into my model.

And OUTPUT:

{
"storeInfo": [
    {
        "storeid": 91,
        "products": [
            {
                "productid": 37,
                "product_name": "hhh",
                "prod_images": "https://sdfsd.com"
            }
        ]
    },
    {
        "storeid": 86,
        "products": [
            {
                "productid": 73,
                "product_name": "ghgjhhj",
                "prod_images": "https://hjhjh.com"
            },
            {
                "productid": 76,
                "product_name": "reer",
                "prod_images": "https://hjhjh.com"
            }
        ]
    }
]
}

Please suggest how I can make the output JSON in this format? I have tried many way to merge two json and make it output to this way. Nothing worked out. Does this suppose to be happened on backed or it is in our frontend hands?

2

There are 2 answers

2
Kayson On

This output model must be built at the api output level.

0
lepsch On

This looks indeed back-end stuff. But if you still need it the following code should do the trick on the front-end.

The merge function merges all properties from both products on json1 and json2 and then formats the output with the provided JSON template.

Check out the live demo on DartPad

import 'dart:convert';

final json1 = {
  "message": "success",
  "data": [
    {
      "storeid": "91",
      "productid": "37",
      "cartitemid": 48,
      "product_quantity": 8
    },
    {
      "storeid": "86",
      "productid": "74",
      "cartitemid": 52,
      "product_quantity": 1
    },
    {
      "storeid": "86",
      "productid": "73",
      "cartitemid": 51,
      "product_quantity": 6
    },
    {
      "storeid": "86",
      "productid": "76",
      "cartitemid": 50,
      "product_quantity": 1
    }
  ]
};

final json2 = {
  "data": [
    {"storeid": 91, "productid": 37, "product_name": "hhh"},
    {"storeid": 86, "productid": 73, "product_name": "dfsdfsd"},
    {"storeid": 86, "productid": 76, "product_name": "dfsdfsd"}
  ]
};

Map<String, dynamic> merge(
    Map<String, dynamic> cart, Map<String, dynamic> namedProducts) {
  final products = <String, Map<String, dynamic>>{};

  // include all cart products
  List<Map<String, dynamic>> cartData = cart['data'];
  for (final p in cartData) {
    final product = {
      ...p,
      'productid': int.parse(p['productid']),
      'storeid': int.parse(p['storeid']),
    };

    products.update(
      '${p['storeid']}:${p['productid']}',
      (value) => {
        ...value,
        ...product,
      },
      ifAbsent: () => product,
    );
  }

  // include all named products
  List<Map<String, dynamic>> namedProductsData = namedProducts['data'];
  for (final p in namedProductsData) {
    products.update(
      '${p['storeid']}:${p['productid']}',
      (value) => {
        ...value,
        ...p,
      },
      ifAbsent: () => {...p},
    );
  }

  // group products by `storeid`
  final storeProducts = <int, List<dynamic>>{};
  products.forEach((key, p) {
    storeProducts.update(
      p['storeid'],
      (value) => [...value, p],
      ifAbsent: () => [p],
    );
  });

  // build final `storeInfo` data
  final storeInfo = <String, dynamic>{
    'storeInfo': [
      for (final entry in storeProducts.entries)
        {
          'storeid': entry.key,
          'products': entry.value,
        }
    ],
  };

  return storeInfo;
}

void main() {
  final storeInfo = merge(json1, json2);
  JsonEncoder encoder = JsonEncoder.withIndent('  ');
  String prettyprint = encoder.convert(storeInfo);
  print(prettyprint);
}

OUTPUT

{
  "storeInfo": [
    {
      "storeid": 91,
      "products": [
        {
          "storeid": 91,
          "productid": 37,
          "cartitemid": 48,
          "product_quantity": 8,
          "product_name": "hhh"
        }
      ]
    },
    {
      "storeid": 86,
      "products": [
        {
          "storeid": 86,
          "productid": 74,
          "cartitemid": 52,
          "product_quantity": 1
        },
        {
          "storeid": 86,
          "productid": 73,
          "cartitemid": 51,
          "product_quantity": 6,
          "product_name": "dfsdfsd"
        },
        {
          "storeid": 86,
          "productid": 76,
          "cartitemid": 50,
          "product_quantity": 1,
          "product_name": "dfsdfsd"
        }
      ]
    }
  ]
}