Javascript JSON is unable to retrieve the tag

Looking at this JSON structure:

{
    "armament": {
        "air_armament": [
            {
                "names": {
                    "russian_name": "R-60",
                    "NATO_name": "AA-8 Aphid"
                },
                "weight": "43.5",
                "explosive_capacity": "3",
                "dynamic_characteristics": {
                    "mach_speed": "2.7",
                    "range": "8",
                    "guidance_system": "infrared"
                },
                "website": "https://en.wikipedia.org/wiki/R-60_(missile)"
            },
            {
                "names": {
                    "russian_name": "R-27",
                    "NATO_name": "AA-10 Alamo"
                },
                "weight": "253",
                "explosive_capacity": "39",
                "dynamic_characteristics": {
                    "mach_speed": "4.5",
                    "range": "80",
                    "guidance_system": "radar"
                },
                "website": "https://en.wikipedia.org/wiki/R-27_(air-to-air_missile)"
            },

            ...

        ]
    }
}

I have a task to extract all the NATO names from the list of air-to-surface missiles, but my current code doesn't seem to be working as expected. Here's what I've tried so far:

function loadList(jsonObj){
            surfaceMissiles = jsonObj.armament.air_surface_missiles;

            for (var i = 0; i < surfaceMissiles.length; i++) {
                natoName = surfaceMissiles[i].names.NATO_name;
                document.getElementById("result").innerHTML += natoName + "<br>";
            }
        }

Unfortunately, it seems like I'm unable to access the specific node I need. Can someone provide guidance on how to solve this issue and successfully retrieve the NATO names from the surface missiles in the JSON data?

Answer №1

Let's start by addressing an issue with a typo in the code snippet below:

var avi = obj_Json.armamento.misil_aire_superficie;

//The corrected version should be (be sure to use var to avoid global scope pollution)
var avi = obj_Json.armament.misil_aire_superficie;

Next, ensure that you correctly parse the JSON object using JSON.parse(yourJsonStringGoesHere) either before passing it to cargarLista() or as the initial step in your function.

var obj = JSON.parse(obj_Json);

Answer №2

The reason for this error is actually a simple typo that needs to be corrected.

    avi = obj_Json.armamento.misil_aire_superficie;

The correct line should read:

    avi = obj_Json.armament.misil_aire_superficie;

Answer №3

Before proceeding, it's important to clarify whether you are dealing with JSON data in string format or as a JSON object.

If the JSON is in string format, you can use the following approach:

function loadList(jsonString){
            json_obj = JSON.parse(jsonString);
            air_missiles = json_obj.armament.air_surface_missile;


            for (var i = 0; i < air_missiles.length; i++) {
                missileId = air_missiles[i].names.nato_name;
                document.getElementById("p1").innerHTML += missileId + "<br>";
            }
        }

After parsing the JSON, you can access the data using "

var missile = json_obj.armament.air_surface_missile;
"

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

Exploring Unanchored Substring Queries in Loopback API

Searching for a solution to implement a basic substring query using the loopback API for a typeahead field. Despite my efforts, I have not been able to find a clear answer. I simply want to input a substring and retrieve all brands that contain that subst ...

Show only the objects in a MongoDB collection that have a matching status in another collection

I have two different collections - one called competition and the other called product. The competition collection contains the objectID of the product, while the product collection contains the competition_status. My goal is to only display the competiti ...

Utilizing Literal and Instance Formats in JavaScript

There are two main methods for creating JavaScript objects. The confusion arises in understanding when to use each notation. Below are examples of both literal and instance variables, each holding different values and producing different results when opera ...

Locate the closest pals near my present whereabouts

Is it possible to find my friends by obtaining their location from their mobile phones when they are near me? I have a code snippet below with the variable cities where I can input the numbers of my friends. Can I achieve this or do I need to make some m ...

Exploring the Possibilities of Socket.io Integration with Express 4 Across Multiple Pages: Dive Into Socket.io Sample Code

Just to clarify, I came across a similar question on Stack Overflow before posting this. However, the answer there was not clear to me and my query is slightly different. Thus, I am hoping for a more straightforward explanation. The Express Generator sets ...

Concealing JSON attributes in Jersey's RESTful services

My goal is to remove any null elements from a RESTFul JSON response if possible. The REST controller is fetching data from a Mongo database, and since these elements do not exist there, I want to ignore them when they are null. Below is my REST Controller ...

Having trouble with an onClick function not working on a .php webpage?

I recently developed a simple JavaScript script that dynamically loads an image based on user input in a text field (e.g., entering 'brick1' loads brick1.jpg). Although this works fine on a regular HTML page, I faced issues triggering the onClick ...

Creating a JavaScript function triggered by a click event that will redirect to

I'm attempting to create an onclick function that will redirect you to a new page when you click on a div element, much like the A + href attribute in HTML. Any suggestions on how to achieve this? Should I just add an A tag inside the div? I'm un ...

"Combining Angular and jQuery for powerful web development

I am looking to develop an application using Angular and incorporate numerous jQuery animations and jQuery UI effects (such as animate, fadeIn, fadeOut, etc). Is it feasible to use jQuery functions in conjunction with Angular? ...

Creating an installation package for an Electron application on Windows

Is it possible to create a Mac installer for an Electron app using a Windows PC? I have tried running npm make, but it only generates a Windows installer. ...

What steps should I follow to run my JavaScript application locally on Linux Mint?

Currently, I am diligently following a tutorial and ensuring that each step is completed accurately. My goal is to locally host my javascript app at localhost:3000. Unfortunately, I am facing difficulties as every attempt to run npm run dev results in an e ...

Storing a component in browser storage using JavaScript and Angular

I am currently working on developing an Angular application that allows users to "favorite" a business card and store it in local memory. I am facing challenges with actually storing the clicked element in the browser's local memory. Furthermore, I f ...

Warning: The use of the outdated folder mapping "./" in the "exports" field for module resolution in the package located at node_modulespostcsspackage.json is deprecated

I recently upgraded my Node to version 16 and since then I have been encountering this issue while building my Angular app. Warning: The folder mapping "./" used in the "exports" field of the package located at ".../node_modules/postcss/package.json" is de ...

Arrange the array to show 8 elements, ensuring to first review the likes object within the array

I am currently iterating through an array of objects in the following manner: <% for(post of posts) { %> <% if(post.likes > 5){ %> <div class="col"> <div class="ca ...

Unable to invoke the setState function within the onSubmit handler of Formik

Every time I submit my form, I want to display an alert. I attempted to pass my state as a prop to the component, but it didn't work. Here's how my class state looks: this.state = { alert_variant: '', alert_heading: ...

how to use jquery to indicate that a checkbox is selected

click here to see the image $(document).ready(function() { $('.editbtn').on('click', function(){ $('#editmodal').modal('show'); $tr=$(this).closest('tr'); var da ...

Utilizing PHP for XML exportation and fetching it through AJAX to integrate it into the DOM, unfortunately, the XML content remains invisible

I've encountered a strange issue with a PHP script that generates valid XML output. I'm trying to fetch this data using an Ajax XMLHttpRequest call in the browser. Although Firebug confirms that the Ajax request is successful and the XML is vali ...

SharePoint 2013 only allows the first AJAX request to work successfully, except when in Edit Mode

I am facing a challenge of making two AJAX requests simultaneously on a SharePoint page. One request originates from the current site, while the other comes from a team site. When I use different URLs (/events) and (/travel), each one works fine when use ...

Styling extracted content using headless browsing algorithm

Is there a way to format the scraped text from multiple elements on the page for use elsewhere? I have JavaScript code that can loop over the elements, add their text to an array, and turn it into a string, achieving the desired formatting. How can I inc ...

Executing a child function from the parent component in React 16

Ever since I upgraded to react 16, I've been encountering null in my console.log(this.child) The Main Component import EditReview from './partials/editReview' class VenueDetails extends Component { constructor(props) { super(props) ...