Retrieving Data from a JSON Object Using a Specific Key

Received a JSON response similar to the one below

{
    "SNGS": {
        "$": {
            "xmlns": "csng",
            "xmlns:ns2": "http://www.w3.org/1999/xlink"
        },
        "Defect": [{
            "$": {
                "id": "DCV19294",
                "ns2:href": "https://mywebsite.com/api/beta//bug/DCSV19294"
            },
            "Field": [{
                "_": "4",
                "$": {
                    "name": "Severity"
                }
            }, {
                "_": "N",
                "$": {
                    "name": "Status"
                }
            }]
        }]
    }
}

Attempting to extract values from the following keys:

  1. id
  2. status

Trying to parse the JSON and retrieve values by key using the code snippet below, but receiving 'undefined' in the alert. Why is that?

const data='{"SNGS":{"$":{"xmlns":"csng","xmlns:ns2":"http://www.w3.org/1999/xlink"},"Defect":[{"$":    {"id":"DCV19294","ns2:href":"https://mywebsite.com/api/beta//bug/DCSV19294"},"Field":[{"_":"4","$":{"name":"Severity"}},{"_":"N","$":{"name":"Status"}}]}]}}'

const parsedData = JSON.parse(data);

console.log(parsedData.id);
console.log(parsedData.Status);

Desiring to extract id (DCV19294) and status (N) from the provided JSON. Assistance would be appreciated.

Answer №1

The reasoning behind the data extraction method is unclear. To access it directly, you can refer to the code snippet below. However, providing more context could lead to a more efficient logic implementation.

const data='{"SNGS":{"$":{"xmlns":"csng","xmlns:ns2":"http://www.w3.org/1999/xlink"},"Defect":[{"$":    {"id":"DCV19294","ns2:href":"https://mywebsite.com/api/beta//bug/DCSV19294"},"Field":[{"_":"4","$":{"name":"Severity"}},{"_":"N","$":{"name":"Status"}}]}]}}'

const parsedData = JSON.parse(data);

const id = parsedData.SNGS.Defect[0].$.id
const name = parsedData.SNGS.Defect[0].Field[1]._

console.log(id, name)

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

Looping Logic in iOS Threads

Can someone please help me with the process of setting up a continuous loop on a thread? I just need some guidance in the right direction. Should I use GCD or NSOperation? I have a JSON file that is updated by a web job every 5 minutes. Is there a method ...

Struggling with retrieving JSON values from jQuery $.ajax to PHP communication

After spending hours browsing SO and trying out various proposed solutions for similar problems, as well as reading the official jQuery Docs, I am still unable to get the following code to work. Any help or hints on what I might be doing wrong would be gre ...

Having difficulty populating the token in the h-captcha-response innerHTML and g-recaptcha-response innerHTML

I am attempting to use 2captcha along with Selenium and Python to bypass an Hcaptcha. After receiving my 2captcha token, I attempt to input it into the textareas labeled 'h-captcha-response' and 'g-captcha-response'. However, this app ...

Delete property from object in JavaScript

Looking for a solution to replace the content of an object with another in an array of objects without passing the reference directly. The challenge is not knowing what values my function will pass, so I can't use them as keys to avoid copying the re ...

The function getResourceAsStream does not return any data

I'm attempting to extract data from a json file and convert it into a java object using a reader: import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import com.google.gson.Gson; import com.google.gson.GsonBuilder; p ...

Sass is throwing an error message saying 'Module not found' during the compilation process

After installing sass using npm ($npm install sass), I attempted to create a JSON script. Unfortunately, when running it, I encountered an error stating 'Cannot find module'. ...

React application created with create-react-app that uses multiple environment files for varying configurations

I've been working on setting up various environment files for a React project (using create-react-app). I referred to the official documentation, but I encountered the following error: '.env.development' is not recognized as an internal or ...

Find the most affordable rate in the JSON data without knowledge of the parent label

I am seeking to extract the best deal from JSON data obtained through an API call and decoded using json_decode. The structure is as follows: products productnumber -> price $product_array['products'][..changingnumber..]['value'] ...

Troubleshooting Issue with React Function's Conditional Component Rendering

Currently, I am working on honing my skills in React using Codesandbox. My goal is to conditionally display a functional React component inside a function (within a class-based component) that triggers when a button is clicked. If you'd like to take ...

Say goodbye to using 'jQuery .load()' with <img> elements inside <a> tags

I have a static HTML page and some other files with the same structure but different content. <div id="textRed" class="scrollbar"> <h1>Header</h1> <p>Lorem Ipsum</p> <a href="images/image1.jpg" data-lightbox ...

I'm running into an InvalidSelectorError and I could use some assistance in properly defining

As I gaze upon a massive dom tree, my task using NodeJS/Selenium is to locate an element by the title attribute within an anchor tag and then click on the associated href. Despite being a newcomer to regex, I am encountering numerous errors already. Below ...

What's the source of this undefined error and is there a way to eliminate it from the code?

After successfully filtering and reducing the data, I encountered an issue with undefined. I am trying to figure out what is causing this and how I can either remove it or make it visible on the screen without being invisible. You can also check the codes ...

I need help determining the starting date and ending date of the week based on a given date

I am looking to determine the starting date (Monday) and ending date of a specified date using Javascript. For instance, if my date is 2015-11-20, then the starting date would be 2015-11-16 and the ending date would be 2015-11-21. ...

Node.js module loader compared to client-side AMD loader such as RequireJS

Today, let's talk about loading Javascript modules on the client-side. There are two popular ways to do this: Using RequireJS Utilizing NPM (Node Package Manager) for exporting and requiring files I've always found the first option to work wel ...

Excess space at the bottom of the Heatmap chart in Highcharts

I am facing an issue with a heatmap having extra space at the bottom that I cannot seem to remove. Despite trying various solutions from different Stack Overflow threads, such as adjusting chart.marginBottom, chart.spacingBottom, x and yAxis margins, and d ...

The ApexChart Candlestick remains static and does not refresh with every change in state

I am currently working on a Chart component that retrieves chart data from two different sources. The first source provides historic candlestick data every minute, while the second one offers real-time data of the current candlestick. Both these sources up ...

What is causing React Js to fail loading css when switching from anchor tag to link tag?

I am learning React and experimenting with creating a basic static website using HTML templates in version ^18.2.0 of React JS. Everything seems to be functioning correctly, however, I have encountered an issue with page refresh. Specifically, when I repla ...

The issue with the smooth scrolling feature in next/link has not been resolved

I am currently facing an issue where smooth scrolling is not working when using next/Link, but it works perfectly fine with anchor tags. However, the downside of using anchor tags is that the page reloads each time, whereas next/link does not reload the pa ...

Cease the execution of promises as soon as one promise is resolved

Using ES6 promises, I have created a function that iterates over an array of links to search for an image and stops once one is found. In the implementation of this function, the promise with the fastest resolution is executed while others continue to run ...

Utilizing Polymer 3 in a different context such as ASP.NET MVC allows for the development of versatile components known as PolymerElements that can be reused

I am currently working on integrating Polymer 3 components into my ASP.NET MVC application. I'm not entirely sure if my approach to this issue is correct at the moment. My main goal is to execute everything from IIS Express. However, I'm encou ...