-1

I know this is an incredibly easy question, but I am struggling with it. Here is a section of the JSON:

 "forecast": {
    "txt_forecast": {
      "date": "7:52 AM MDT",
      "forecastday": [
        {
          "period": 0,
          "icon": "partlycloudy",
          "icon_url": "http://icons.wxug.com/i/c/k/partlycloudy.gif",
          "title": "Thursday",
          "fcttext": "Partly cloudy. High near 90F. Winds W at 10 to 15 mph.",
          "fcttext_metric": "Sunshine and clouds mixed. High 32C. Winds W at 15 to 25 kph.",
          "pop": "10"
        },
        {
          "period": 1,
          "icon": "nt_partlycloudy",
          "icon_url": "http://icons.wxug.com/i/c/k/nt_partlycloudy.gif",
          "title": "Thursday Night",
          "fcttext": "Partly cloudy skies. Low 71F. Winds SSE at 5 to 10 mph.",
          "fcttext_metric": "Partly cloudy. Low 22C. Winds SSE at 10 to 15 kph.",
          "pop": "0"
        },

And here is the code that I have on my website:

    <script>
        jQuery(document).ready(function($) {
            $.ajax({
                url : "http://api.wunderground.com/api/b18485d6da512c58/geolookup/forecast/q/UT/SLC.json",
                dataType : "jsonp",
                success : function(parsed_json) {
                    var title = parsed_json['forecast']['txt_forecast']['forecastday']['period.0']['title'];
                    document.getElementById('day').innerHTML = title;
                    }
            });
        });
    </script>

I want to assign the value of title within period 0 to the variable 'title'. How do I do that?

Thanks.

SMPLGRP
  • 251
  • 3
  • 8
  • 22

3 Answers3

2

forecastday is an array, So you need to use index to element.

Use

var title = parsed_json['forecast']['txt_forecast']['forecastday'][0]['title'];
                                                                  ^...............

However, You can simply use dot notation

var title = parsed_json.forecast.txt_forecast.forecastday[0].title;
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Still a bit of a noob, but this might work:

var title = parsed_json['forecast']['txt_forecast']['forecastday'][0].title;
Andy
  • 61,948
  • 13
  • 68
  • 95
joesch
  • 347
  • 1
  • 5
  • 17
1

You're better off using dot notation here, and ensure that you use the corrent element of the array:

var title = parsed_json.forecast.txt_forecast.forecastday[0].title;

DEMO

Andy
  • 61,948
  • 13
  • 68
  • 95