VishnuKc
VishnuKc

Reputation: 13

How to access .json file in flutter?

I was given a json dataset dataset.json, which has the data:

[
     {
       "id": 1,
       "title": "Class 1",
       "videoUrl":
           "https://tech-assignments.yellowclass.com/1213_shipra_mam_7_papercrumpling_ice_cream/hls_session/session_video.m3u8",
       "coverPicture": "https://picsum.photos/800/450"
     },
     {
       "id": 2,
       "title": "Class 2",
       "videoUrl":
           "https://tech-assignments.yellowclass.com/1215_shipra_mam_8_papercruumpling_birthday_cap_1/hls_session/session_video.m3u8",
       "coverPicture": "https://picsum.photos/800/450"
     },
     {
       "id": 3,
       "title": "Class 3",
       "videoUrl":
           "https://tech-assignments.yellowclass.com/1216_shipra_mam/hls_session/session_video.m3u8",
       "coverPicture": "https://picsum.photos/800/450"
     },
];

This is just a sample, actually it has 60 ids("id": 60). Now I need to access this data and how am I supposed to do that?

And if I want to access a particular data what should I do? for example: I want to access video url from this dataset, how do i do that?

Upvotes: 0

Views: 75

Answers (1)

user18309290
user18309290

Reputation: 8380

Add it to the assets

flutter:
  assets:
    - assets/dataset.json

Load it from the assets

import 'package:flutter/services.dart' show rootBundle;

final jsonString = await rootBundle.loadString('assets/dataset.json');

See Adding assets and images for details.

Decode it

import 'dart:convert';

final dataset = jsonDecode(jsonString);
final firstVideoUrl = dataset.first['videoUrl'];

See JSON and serialization for details.

Upvotes: 1

Related Questions