Unable to retrieve the specific value associated with a key from JSON data

I am attempting to retrieve the value of "id" from a JSON response I received after making a POST request.

{
"callId": "87e90efd-eefb-456a-b77e-9cce2ed6e837",
"commandId": "NONE",
"content": [
    {
        "scenarioId": "SCENARIO-1",
        "Channel": "Channel1-1",
        "data": {
            "section": {
                "class": {
                    "repository": [
                        {
                            "export": "export-1",
                            "modules": "module-1",
                            "index": "23",
                            "period": {
                                "axis": {
                                    "new_channel": "channel-1.1"
                                },
                                "points": [
                                    {
                                        "id": "6a5474cf-1a24-4e28-b9c7-6b570443df9c",
                                        "duration": "150",
                                        "v": 1.01,
                                        "isNegligible": false
                                    }
                                ]
                            }
                        }
                    ]
                }
            }
        }
    }
]
}

I can see the entire response json and successfully extract the value of "callId" using the code below. However, an error occurs on the last line:

Cannot read property '0' of undefined

Code snippet:

function callback(error, response, body) {
  if (!error && response.statusCode == 200) {
    let responseData = JSON.stringify(body);
    //Display the entire response
    console.log(responseData);
    //Display the callId
    console.log(body['callId']);
    //Error occurs here
    console.log(body.content[0].repository[0].points[0].id);
  }
}

Is there any solution to retrieve the value of "id"?

Answer №1

At this moment, your goal is to retrieve the id from

body.content[0].repository[0].points[0]
.

If you analyze it closely, repository[0] represents an object without any immediate child points.

Hence, accessing repository[0].points will result in undefined and attempting to access repository[0].points[0] leads to trying to access property 0 of undefined, causing an error. To correctly obtain the id, use the following path:

body.content[0].data.section.class.repository[0].period.points[0].id

If you are unsure about parsing JSON data, consider breaking it down by logging body and then expanding it in the console or using a JSON editor.

Note: It is advisable to validate whether each value exists at each level before accessing deeper nested elements. For instance, if your body does not contain a certain value like content, attempting to access body.content[0] will trigger an error. Therefore, it's recommended to perform checks at each level as shown below:

if(body){
    if(body.content){
        if(body.content[0]){
            /* and so forth */
        }
    }
}

Answer №2

Give it a shot

Use console.log to output the id of the first point in the repository's section data

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

While using Appium/Protractor for testing a Cordova app, I encountered an issue when running a simple test. The test failed with an error message stating: "Failed to get sockets matching: @web

I'm facing an issue while trying to perform a simple test on my hybrid app using Appium + Protractor. The error message I am encountering is: Failed to get sockets matching: @webview_devtools_remote_.*15239 I have Ubuntu installed and have set up App ...

Utilizing HP OO inputs alongside REST API integration

Currently, I am utilizing HP Operations Orchestration software to automate flows. My current task involves resuming a flow by providing inputs to steps. The JSON body format being used is as follows: { "action":"RESUME", "data":{ "branchId" : null, "in ...

Combine two closely related functions into a single function

I'm dealing with two very similar functions: setEndTimesAndStartTimes(pricerules: PriceRule[], type: string) { this.endTimes = []; this.startTimes = []; pricerules.forEach(pricerule => { if (type === 'end') { ...

scala handling missing fields during JSON serialization in json4s

I've been utilizing json4s for serializing scala map objects. import org.apache.spark.util.StatCounter import org.json4s.DefaultFormats val myMap: scala.collection.Map[String, Map[String, StatCounter]] = Map("key" -> Map("secondKey" -> StatCou ...

I'm having trouble with implementing a basic show/hide feature for the login and logout options in the navigation bar using Angular. Can anyone help me figure out why it's

Is there a way to display the functionality after logging in without using session storage or implementing the logout function? The HTML for navigation is provided below. <nav class="navbar navbar-expand-sm navbar-light bg-light"> ...

Exploring the usage of array map parameters in rxjs 6 when combined with withLatestFrom

Prior to Rxjs 6, we were able to achieve the following: interface TypeA { payload: any; } source$.pipe( withLatestFrom(source2$, (source1: TypeA, source2: TypeB) => ({ payload: source1.payload, source2 }) ), ) In the resultSelector method ...

Ways to rearrange an object with javascript

I am looking to restructure my object by removing a nesting. How can I achieve this using JavaScript? Actual: var a = [ { clickedEvents: { 'event-element': 'a', 'event-description': & ...

"An error occurred in Pyrebase: The 'orderBy' parameter must be a properly formatted JSON path

I am utilizing Firebase and my JSON data in Firebase looks like this. I aim to extract the key values (288xxx) based on the busStopName values. https://i.sstatic.net/wzzEa.png The code I have written is shown below. Let's use '윤정사앞&apos ...

How to retrieve all the text inside an element using Protractor and Selenium

<div class="test"> <span> <div>CONTENT </div> </span> <div> <ul> <li> <span>More text</span> EXAMPLE1</li> <li>EXAMPLE2</li> ...

How to retrieve a JSON array from a CSV file stored remotely using PHP

In one of my PHP scripts, I need to convert data from a remote CSV file into a JSON array. The URL of the remote CSV file is: www.xyz.com/dir/records.csv NAME Age ID Jhon 45 101 Bhil 42 102 Tone 41 103 I am looking for a function that can ...

Working with JSON data in Angular 2 constructor

When sending a JSON response from the server, it is in the format shown below: {id: Int, name: String, childJSON: String} I want to map this data to the following TypeScript classes: export class Student{ constructor(public id: string, ...

Building a Custom Dropdown Select List with FormControlName and ControlValueAccessor in Angular 8

Does anyone have a working solution for creating a Material dropdown wrapper (mat-select dropdown) that can be used with formControlName? If so, could you please share a Stackblitz demo of your implementation? Here are the requirements: Should work seam ...

Having trouble with Laravel 5.2 - Left Join and DB::Raw not functioning properly?

I am facing an issue with my query where I am attempting to utilize DB::Raw() for the left join but I keep encountering an error: Missing argument 2 for Illuminate\Database\Query\Builder::leftJoin() Here is the query causing the problem: ...

Transforming Several Dropdowns using jQuery, JSON, and PHP

Hey there! I'm looking to update the state depending on the country and city based on the chosen state. <label>Country:</label><br/> <select onchange="getval(this)"> <option value="">Select Country</op ...

How to upload files from various input fields using Angular 7

Currently, I am working with Angular 7 and typescript and have a question regarding file uploads from multiple input fields in HTML. Here is an example of what I am trying to achieve: <input type="file" (change)="handleFileInput($event.target.files)"&g ...

The correct method for creating an external JSON file

As I browse through numerous JSON tutorials online, including those on STO, I find myself in a state of confusion when it comes to determining the right approach for writing an external JSON file. I have come across various examples such as: (although Ad ...

Issue TS1112: It is not possible to declare a class member as optional

I'm currently working on creating a movie catalog using Angular and Ionic. Within the Movie class, I have properties for id, title, image, and plot. On the initial page of the app, only the id, title, and image are displayed, while the plot is omitte ...

The unit test is not passing due to inconsistencies between the mock data generated in the constructors and the original mock data

Currently, I am delving into the world of unit testing and have created a test to work on. Here is what I have so far: const EXEPECTED: MergedFood = { id: '1', name: 'test mergedFood', ingredients: { '2': ...

I'm having trouble linking MikroORM migration to Postgresql - the npx command keeps failing. Can anyone offer some guidance on what

I am encountering a situation similar to the one described in this post. I'm following Ben Awad's YouTube tutorial: you can see where I am in the tutorial here. Objective: My goal is to execute npx mikro-orm migration:create in order to generate ...

The Controller is failing to pass JSON Data to the AJAX Call

When trying to access JSON data in the Controller, it is not being retrieved in the Success function and instead showing an error message "Failed to load resource: the server responded with a status of 406 (Not Acceptable)" or executing the Error function. ...