Back

Realtime - Problem with getting data from received JSON format

  • 0
  • Flutter
  • Realtime
Ichigor
2 May, 2023, 09:59

Hi!

I'm listening to a specific document:

TypeScript
final realtime = Realtime(client);

    final subscription = realtime.subscribe([
      'databases.64046c8b50eba8c807d0.collections.6405162fd68c7c61df67.documents.642a0de5238de5eb9e3a'
    ]);

    subscription.stream.listen((response) {
      // A callback will be made on changes for documents A and all files.

      String jsonString = '${response.payload}';

      print(jsonString);
    });

and I get JSON like this:

TypeScript
{ first_name: Badma, userId: 642a0de3d38b4848156571, scores: 7, progress: 0.0001, errors: [], alchiki: 20, createdAt: 2023-04-03T02:21:08.785+00:00, friends: [6411842dda40129372d1, 6410dbd3bf73ca111c18], refcode: D9QSY, resultCheckRefered: null, userRefer: mqB8o, checkRefered: 2, image: null, $id: 642a0de5238de5eb9e3a, $createdAt: 2023-04-02T23:21:09 145+00:00, $updatedAt: 2023-05-02T09:48:37.380+00:00, $permissions: [read("user:642a0de3d38b48156571"), update("user:642a0de3d38b48156571"), delete("user:642a0de3d38b48156571")], $collectionId: 6405162fd68c7c61df67, $databaseId: 64046c8b50eba8c807d0}

When I try to execute:

TypeScript
subscription.stream.listen((response) {
      // The callback will be executed on changes for document A and all files.

      String jsonString = '${response.payload}';

     Map<String, dynamic> data = jsonDecode(jsonString);
     int scores = data['scores'];
   
      print(scores);
    });```

and get the scores data, the application crashes with an error:

see screen

what am I doing wrong?
TL;DR
The user is experiencing an issue when trying to retrieve data from a received JSON format using the `jsonDecode` function. They receive an error and are unsure what they are doing wrong. The solution is to note that `response.payload` is already a `Map<String, Dynamic>`, so there is no need to use `jsonDecode` on it. They can directly access the values in `response.payload` using the appropriate keys.
Maniac_Fighter
2 May, 2023, 12:49

response.payload is already a Map<String,Dynamic>. JsonDecode is not required here

Reply

Reply to this thread by joining our Discord

Reply on Discord

Need support?

Join our Discord

Get community support by joining our Discord server.

Join Discord

Get premium support

Join Appwrite Pro and get email support from our team.

Learn more