5

I have this JSON file I want to fetch "name" field but I a have not better understanding about JSON file can anyone please explain how can I read this JOSN file format and How can I access "name" field to print. I have tried multiple code but I did not make it successful.

{
    "stream": {
        "tv": [{
            "name": "Tv",
            "description": "Tv",
            "url": "this is the url",
            "image": "imagelink",

        }]
    }
}

Here is the Code

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() => runApp(HomePage());

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
  List data=[];
  @override
  void initState() {
    fetchData();
    super.initState();
  }

  void fetchData() async {
    final response =
    await http.get('Link here');
    if (response.statusCode == 200) {
      setState(() {
        data = json.decode(response.body);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: Text(data[0]["stream"]["adomtv"][0]["name"]),// how can I access given Json fields here 
      )
    );
  }
}
8
  • stackoverflow.com/a/51360517/8358956 Commented Sep 23, 2019 at 18:18
  • github.com/nisrulz/flutter-examples/tree/master/load_local_json Commented Sep 23, 2019 at 18:19
  • It is not worthy in my case my JSON file format is change.the other one you are referring I successfully work on that but Unable to work on this format. like nested object or nested curly braces I have in my file which is confusing. Commented Sep 23, 2019 at 18:39
  • 1
    You can parse this json as a string and then use your model class’s fromJson method to get actual value object from the parsed string. Commented Sep 23, 2019 at 18:41
  • thanks Sharad paghadal, it will be more helpful if you code for it please Commented Sep 23, 2019 at 18:50

5 Answers 5

2

So I have tried this:

import 'dart:convert';

main() {
  String jsonS = """{
    "stream": {
        "tv": [{
            "name": "Tv",
            "description": "Tv",
            "url": "this is the url",
            "image": "imagelink"

        }]
    }
}""";
  var myMap = json.decode(jsonS);
  var myName = myMap['stream']['tv'][0]['name'];
  print('${myName}');
}

This works as expected and produces the name of the Tv.

However, I think you have a typo in your json. My guess is that you are getting a stream of objects, one of which is the Tv. So I would expect your json to look more like:

{ 
        "stream": { [
            {
                "name": "Tv",
                "description": "Tv",
                "url": "this is the url",
                "image": "imagelink"

            },
            {
                "name": "Radio",
                "description": "Radio",
                "url": "this is the url",
                "image": "imagelink"

            },

]}

If that is the case you just need data['stream'][0]['name'] for the TV and data['stream'[1]['name'] for the radio. So my advice is check the server data stream carefully.

Hope this helps.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply Chris. I do not want to change the format of my JSON is all correct. but one thing when I put [ ] these bracket to outside of my JSON I can access json easily without it I am not able enough. if you think I have wrong format of my JSON kindly explain the error because the format you wrote is not required.
Basically, you need to use ["words"] to navigate curly brackets and [number] to navigate square brackets. Thats all I can suggest.
@ChrisReynolds could you please give my question a look? I'm facing a similar problem. stackoverflow.com/questions/61548143/…
1

Look you have list type data List data=[]; that require the index in integer value so if you have it as string you can use the way you want. If you want to access it like this and you are handle the JSON as well than convert JSON a little bit

{
    "stream": {
        "tv": [{
            "name": "Tv",
            "description": "Tv",
            "url": "this is the url",
            "image": "imagelink",

        }]
    }
}

Convert it into

[
{
    "stream": {
        "tv": [{
            "name": "Tv",
            "description": "Tv",
            "url": "this is the url",
            "image": "imagelink",

        }]
    }
}
]

Now you can access the way you are want. this will work for you know data[0]["stream"]["adomtv"][0]["name"]

2 Comments

ok go and update the json and run this code in case there is any issue let me know.
Thanks again sir this is the real mistake I was making I update the Json according to the answer and upload to server now my all code working good. You are saving my time thanks and always stay blessed and happy. :)
1

You need to decode the json String, for example:

Settings settingsFromJson(String str) {
  final jsonData = json.decode(str);
  return Settings.fromJson(jsonData);
}

and then you can access as an array

1 Comment

Thanks for you answer Marcio. I was successfully read another Json by doing so Text(data[0]["name"]) so but I am not able to get through
0

Here is the doc and here

jsonDecode() returns a Map so i believe the access would be

data["stream"]["tv"][0]["name"]

2 Comments

I did try this also before posting the question and I was getting error "The argument type 'String' can't be assigned to the parameter type 'int'." like compiler need to have Ist data as integer to know the index of the json file. how can i get rid of the problem that is the real issue.
I even did try this Text(data[0]["stream"]["tv"][0]["name"]), by doing so I get error "RangeError (index): Invalid value: Valid value range is empty: 0"
0

Currently it looks like your code has a typo. adomtv rather than tv.

1 Comment

Thanks for your reply Chris but just consider that written Json file instead of that link. I just update the question. I just need to know the sequence to access "name" attribute.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.