Parsing JSON data in JavaScript with multiple objects

I just received a JSON Object from an HTTP request

[
  {
    "location": {
      "name": "Seattle, WA",
      "lat": "47.604",
      "long": "-122.329",
      "timezone": "-7",
      "alert": "",
      "degreetype": "F",
      "imagerelativeurl": "http:\/\/blob.weather.microsoft.com\/static\/weather4\/en-us\/"
    },
    "current": {
      "temperature": "81",
      "skycode": "32",
      "skytext": "Sunny",
      "date": "2015-08-09",
      "observationtime": "18:00:00",
      "observationpoint": "Seattle, WA",
      "feelslike": "81",
      "humidity": "39",
      "winddisplay": "3 mph Northwest",
      "day": "Sunday",
      "shortday": "Sun",
      "windspeed": "3 mph",
      "imageUrl": "http:\/\/blob.weather.microsoft.com\/static\/weather4\/en-us\/law\/32.gif"
    },
    "forecast": [
      {
        "low": "60",
        "high": "81",
        "skycodeday": "29",
        "skytextday": "Partly Cloudy",
        "date": "2015-08-08",
        "day": "Saturday",
        "shortday": "Sat",
        "precip": ""
      },
      {
        "low": "65",
        "high": "82",
        "skycodeday": "34",
        "skytextday": "Mostly Sunny",
        "date": "2015-08-09",
        "day": "Sunday",
        "shortday": "Sun",
        "precip": "0"
      },
      {
        "low": "66",
        "high": "82",
        "skycodeday": "32",
        "skytextday": "Sunny",
        "date": "2015-08-10",
        "day": "Monday",
        "shortday": "Mon",
        "precip": "0"
      },
      {
        "low": "68",
        "high": "83",
        "skycodeday": "30",
        "skytextday": "Partly Sunny",
        "date": "2015-08-11",
        "day": "Tuesday",
        "shortday": "Tue",
        "precip": "0"
      },
      {
        "low": "65",
        "high": "88",
        "skycodeday": "32",
        "skytextday": "Sunny",
        "date": "2015-08-12",
        "day": "Wednesday",
        "shortday": "Wed",
        "precip": "0"
      }
    ]
  }
]

Here's the current code I have to process it:

var responseObject = JSON.parse(xhr.responseText);
var newContent = '';
for (var i = 0; i < xhr.responseText.length; i++) {
    newContent += '<div class = "location">';

    //newContent += '<p><b>' + xhr.responseText[i].location.pid + '</b><br>';

    newContent += '<p> Name: <b>' + responseObject.location[i].location + '</b><br>';
    newContent += '<p> Lat: <b>' + responseObject.location[i].lat + '</b><br>';
    newContent += '<p> Long: <b>' + responseObject.location[i].long 
                   + '</b>    <br>';
    newContent += '<p> TimeZone: <b>' + responseObject.location[i].timezone +  
                   '</b><br>';
    newContent += '<p> Alert: <b>' + responseObject.location[i].alert + '</b><br>';
    newContent += '<p> DegreeType: <b>' + responseObject.location[i].degreeType + '</b><br>';
    newContent += '</div>';
}

The issue I am facing is that there are three different objects within one JSON object. How can I traverse through it? I'm quite new to parsing JSON data.

Answer №1

This is an example of how you could iterate through the response array that has been received.

var responseObject = JSON.parse(xhr.responseText),
    newContent = '',
    location = responseObject[0].location,
    current = responseObject[0].current,
    forecast = responseObject[0].forecast;

newContent += '<div class = "location">';
newContent += '<p> Name: <b>' + location.name + '</b><br>';
newContent += '<p>Lat: <b>' + location.lat + '</b><br>';
newContent += '<p>Long: <b>' + location.long + '</b><br>';
newContent += '<p>TimeZone: <b>' + location.timezone + '</b><br>';
newContent += '<p>Alert: <b>' + location.alert + '</b><br>';
newContent += '<p>degreeType: <b>' + location.degreeType + '</b><br>';
newContent += '</div>';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to set functions as variables within an if statement in JavaScript and then not be able to call them later?

My validation process involves a multi-function where I don't invoke a master function beforehand to check and validate inputs. Within my "SignUp Function", I have implemented a validation function as variables that are checked before passing to the r ...

After refreshing the page, the local storage does not appear

I've been struggling to get it working for hours with no luck. After submitting the form, I create local storage values for name, surname, and email so that they can be automatically filled in the form next time without requiring the user to retype th ...

Adding the "@" symbol as part of an object name in JSON using PHP

Need to generate JSON using PHP with certain content { "@context":"something", "type":"something" } Decided to create a custom class class doc { public $context; public $type; } Unfortunately, the JSON output does not include the @ si ...

What is the process for transforming a JSON file into a parser using argparse?

Here is a sample json file: { "model_name_or_path": "microsoft/layoutlmv3-base", "config_name": null, "tokenizer_name": null, "cache_dir": null, "model_revision": "main", "use_auth_token": false } I am looking to convert this JSON ...

The test may detect a variable that was not initialized

I'm trying to understand why I get the error message "variable may not have been initialized" when testing (variable === "some text"), but I don't receive the same error when using (typeof passwordHashOrg !== 'undefined') The code that ...

"Using a WMD Editor to show the content of the wmd-preview division and questions on how to save this content in a

I am currently in the process of integrating the WMD editor into my website. Everything seems to be functioning correctly so far, but I have hit a roadblock: How can I store the entered information in my database? I have developed a JS/Ajax function that a ...

Is the order of execution of extraReducers before or after the reducers?

I was curious about the createSlice function in redux-toolkit and how it handles the order of execution for extraReducers compared to reducers. Can we determine if the extraReducers are executed before or after the reducers, or is the order indeterminate? ...

Update the text content in the specific span element when the class attribute matches the selected option in the

How can I dynamically update text inside a span based on matching classes and attributes without hardcoding them all? An ideal solution would involve a JavaScript function that searches for matches between span classes and select field options, updating t ...

An essential component of Chai assertion is the inclusion of "or"

While attempting to iterate through a list of elements, I am looking to verify that the body contains either of two values. However, the current assertion method only allows me to check for one value: expect(cellText).includes(toDateFormat); Is there a wa ...

What is the best way to simulate an external class using jest?

My Vue page code looks like this: <template> // Button that triggers the submit method </template> <script> import { moveTo } from '@/lib/utils'; export default { components: { }, data() { }, methods: { async ...

Decode a JSON entity featuring a distinct layout and identical identifier

I have developed an application that utilizes web scraping techniques to extract movie information from IMDb. The movie data is obtained by parsing the source code of the respective movie pages, some of which are formatted in JSON using the "Schema.org" mo ...

Verify if any choices are available before displaying the div block

I need to determine if there is a specific option selected in a dropdown menu, and then display a div if the option exists, otherwise hide it. I'm not just checking the currently selected option, but all available options. if (jQuery(".sd select opti ...

Can you guide me on how to establish a cookie within a selenium webdriver javascript script?

I am trying to figure out how to set a cookie using a basic webdriver script: WDS.sampleResult.sampleStart(); //WDS.driver.manage().addCookie(new Cookie("connect.sid", "s%3AeexeZcd_-S23Uh30e3Dmd4X9PskWF08s6m5hDurDa5Jj66SupmmiqvKEjAg6HGigl0o0V%2B9R7m4", ...

Leveraging CSS or JavaScript for Displaying or Concealing Vacant Content Sections

I'm working on developing a page template that utilizes section headers and dynamically pulled content from a separate database. The current setup of the page resembles the following structure: <tr> <td> <h3> ...

I need to figure out a way to validate form data dynamically as the number of fields constantly changes. My form data is being sent via Ajax

Click validation is desired. It is requested that before transmitting data, the validate function should be executed. If there is an empty field, a message should be displayed and the data should not be sent to the PHP file. In case there are no empty fi ...

Troubleshooting: jQuery $.post not functioning as expected in certain circumstances

I'm currently experimenting with inserting data into a MySQL database using AJAX and jQuery's $.post method. To test this functionality, I have created the following setup: In my index.html file (which already includes jQuery for various other f ...

Using parseFloat in JavaScript for German number formatting

Currently, I am working on incorporating a Vue.js component that is inspired by the example provided in this link: https://jsfiddle.net/mani04/bgzhw68m/. This is the structure of my source code: computed: { displayValue: { get ...

Using jq to retrieve particular information from varying map titles belonging to identical categories

My current task involves querying the vault API to retrieve a list of entities by their Ids and extracting alias names from aliases.name. However, I am facing difficulty in extracting the values due to the unique map names in each iteration. Command curl ...

What are the steps needed to establish a distinct data scope in AngularJS along with the application of filters?

I’m currently practicing my skills in AngularJS and I have been experimenting with creating reusable components. At this stage, I have successfully created a component using the directive method. However, I now have some doubts that I need clarification ...

Issues with jQuery AJAX, occasionally experiencing repeated requests

Currently, I am in the final stages of revamping our JavaScript system by transitioning from Prototype to jQuery. We have numerous AJAX requests that are triggered when specific events occur on certain elements. One instance of this is when a new event is ...