0

This is the JSON data and I'm trying to access the date and the open value with this code but I'm getting errors. What would the proper syntax be?

factory Stock.fromJson(Map<String, dynamic> json) { // parse the json into data we can use
    return Stock(
      date: json['Time Series (Daily)[0]'],
      open: json['Time Series (Daily[0].open'],
      high: json['Time Series (Daily[0].high'],
      low: json['Time Series (Daily[0].low'],
      close: json['Time Series (Daily[0].close'],
      volume: json['Time Series (Daily[0].volume']
    );
  }
{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "MSFT",
        "3. Last Refreshed": "2020-03-26",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2020-03-26": {
            "1. open": "148.4000",
            "2. high": "156.6600",
            "3. low": "148.3700",
            "4. close": "155.8800",
            "5. volume": "64143669"
        }
}

1 Answer 1

1

To get json objects or values of your json data, you need to pass attributes names and manipulate the json object

factory Stock.fromJson(Map<String, dynamic> json) { // parse the json into data we can use
return Stock(
  date: json['Time Series (Daily)']['2020-03-26'],
  open: json['Time Series (Daily)']['2020-03-26']['1. open'],
  ...
);

}

You can also convert your json to dart object with this tool : https://javiercbk.github.io/json_to_dart/

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

9 Comments

Thanks! What if I don't know the dates, when I try json['Time Series (Daily)'][0]['1. open'] to get the first date, it comes back null.
Because it's not a list. It's a map of <String, dynamic>. You have to convert to a list like this : json['Time Series (Daily)'].values.toList()[0]['1. open']
Wow thank you so much for all this help. In the future, do you think there is a better source I could've checked before stack overflow? I couldn't find this part you helped me with on YouTube or the official docs or by searching stack overflow.
Stackoverflow is a good place to find help. However, the official documentation of Flutter and json serialisation is pretty clear flutter.dev/docs/development/data-and-backend/json
Yeah I think my confusion stemmed from the fact that the official documentation didn't seem to have an example with nested JSON and I didn't realize I had to convert to list form. Just trying to improve so I bet I won't be making this mistake again. Thanks for all the help
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.