user13410550
user13410550

Reputation:

JSON Data To Array in Flutter

The below code is decoding the Json Data for which the console output is also shown and the json data is also shown. I am able to decode the data successfully as per the console output. I want the decoded json data to be stored in an array so that I can store it in firestore document as an array.

How should I do that? I know how to store data in firestore database, all I need to store the json data in an array. Please guide me

CODE

 var parsedData = json.decode(state.successResponse);
                List members = parsedData['members'];
                 members.forEach((member){
               
                  String name1 = member['firstName'];
                 print(name1);
       });

JSON DATA

flutter: {
    "members": [
        {
            "firstName": "Michael"
        },
        {
            "firstName": "Jennifer"
        },
        {
            "firstName": "Lisa"
        }
    ]
}

CONSOLE OUTPUT

flutter:Michael
flutter:Jennifer
flutter:Lisa

Upvotes: 0

Views: 96

Answers (1)

Alok
Alok

Reputation: 9008

ANSWER 2.0

If the case is to store the data into the array, then we need to have a List<String> which will store the firstname param. You can then use _firstNames list to be passed to your firestore

    // This will store the name from the data
    List<String> _firstNames = [];
    var parsedData = json.decode(state.successResponse);
    List members = parsedData['members'];
    members.forEach((member){
         // simply add it to the list the data
         _firstNames.add(member['firstName']);
    });

    // print it to check, whether you have got it or not, 
    // outside the loop
    print(_firstNames);

I will give out demo as per your data set only in this code example

  List<String> _firstNames = [];
  Map _membersData = {
    "members": [
        {
            "firstName": "Michael"
        },
        {
            "firstName": "Jennifer"
        },
        {
            "firstName": "Lisa"
        }
    ]
  };
  
  _membersData["members"].forEach((data){
    _firstNames.add(data["firstName"]);
  });
  print(_firstNames);

  // OUTPUT will be [Michael, Jennifer, Lisa]

Try it and let me know

Upvotes: 1

Related Questions