Having trouble extracting a value from a JSON object in JavaScript

I am encountering an issue while attempting to extract a specific value nested within a JSON object. The API call response is provided below.

var responseData = {
  "statusCode": 200,
  "body": "{\"Errors\":\"\",\"Message\":null,\"OrgID\":0,\"Output\":\"{\\\"AllUserDetails\\\":{\\\"UserDetails \\\":[{\\\"UserID\\\":1012,\\\"UserName\\\":\\\"Arul, Velu\\\",\\\"EmpID\\\":null,\\\"Role\\\":\\\"SA\\\",\\\"RoleName\\\":\\\"Super Admin\\\",\\\"EmailID\\\":\\\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fabb888f968c9f968fba9d979b9396d4999597">[email protected]</a>\\\",\\\"NT_UID\\\":\\\"ICS\\\\\\\\RNair\\\",\\\"Frm_UID\\\":\\\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d495a6a1b8a2b1b8a194b3b9b5bdb8fab7bbb9">[email protected]</a>\\\",\\\"Frm_PWD\\\":\\\"3ZD1KS+4gEL5RKsjlC5k0MIfaiV8k\\/ixZRS6NpNyu0g=\\\",\\\"Org_Id\\\":1,\\\"Instance_Model\\\":\\\"Dependent\\\",\\\"Org_Name\\\":\\\"India\\\",\\\"AccessCreate_Portfolio\\\":false,\\\"AccessEdit_Portfolio\\\":false,\\\"Customer\\\":2592,\\\"Customer_Name\\\":\\\"ICS\\...
  
  // Remaining content trimmed for brevity
  

Although I was successful in extracting the body value using responseData.body, I am facing challenges retrieving the value inside

body.Output.AllUserDetails.UserDetails [0].UserID
. An error mentioning 'AllUserDetailsis undefined' is being displayed. Can anyone provide guidance on this issue?

Answer №1

Give this a shot:

Access the UserID from the api response by using the following code snippet: JSON.parse(JSON.parse(responseData.body).Output).AllUserDetails['UserDetails '][0].UserID

Just a heads up - there is an additional space in the UserDetails key within the api response, so make sure to access it using bracket notation instead of dot notation.

Answer №2

Here is a straightforward solution:

Access the desired attribute after parsing the JSON data twice: JSON.parse(JSON.parse(responseData.body).Output)

Next, extract any specific attribute you require.

A more detailed explanation:

The data within your object is in string format and not as an object.

Answer №3

Performing multiple iterations of JSON.parse is necessary in order to access the user details.

var responseData = {
  "statusCode": 200,
  "body": "{\"Errors\":\"\",\"Message\":null,\"OrgID\":0,\"Output\":\"{\\\"AllUserDetails\\\":{\\\"UserDetails \\\":[{\\\"UserID\\\":1012,\\\"UserName\\\":\\\"Arul, Velu\\\",\\\"EmpID\\\":null,\\\"Role\\\":\\\"SA\\\",\\\"RoleName\\\":\\\"Super Admin\\\",\\\"EmailID\\\":\\\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="29685b5c455f4c455c694e44484045074a4644">[email protected]</a>\\\",\\\"NT_UID\\\":\\\"ICS\\\\\\\\RNair\\\",\\\"Frm_UID\\\":\\\"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c2d1e19001a0900192c0b010d0500420f0301">[email protected]</a>\\\",\\\"Frm_PWD\\\":\\\"3ZD1KS+4gEL5RKsjlC5k0MIfaiV8k\\/ixZRS6NpNyu0g=\\\",\\\"Org_Id\\\":1,\\\"Instance_Model\\\":\\\"Dependent\\\",\\\"Org_Name\\\":\\\"India\\\",\\\"AccessCreate_Portfolio\\\":false,\\\"AccessEdit_Portfolio\\\":false,\\\"Customer\\\":2592,\\\"Customer_Name\\\":\\\"ICS\\\",\\\"Location\\\":null,\\\"Location_Name\\\":\\\"\\\",\\\"Userlevel\\\":2544,\\\"User_Level\\\":\\\"Analyst\\\",\\\"Country\\\":null,\\\"Designation\\\":\\\"Consultant\\\",\\\"ContactNo\\\":\\\"2133232123\\\",\\\"MobileNo\\\":null,\\\"JoinDate\\\":\\\"2016-01-06 00:00:00\\\",\\\"Access_ServerMon\\\":false,\\\"Access_IncidentMgmt\\\":true,\\\"Access_CMCMDB\\\":true,\\\"Access_CMDB\\\":true,\\\"Access_RM\\\":true,\\\"Access_KnowledgeMgmt\\\":true,\\\"Access_PortfolioMgmt\\\":true,\\\"Access_ServiceRequest\\\":true,\\\"Access_ServiceCatalog\\\":true,\\\"Access_NetworkMon\\\":false,\\\"Access_AssetMgmt\\\":true,\\\"Access_ProblemMgmt\\\":true,\\\"Access_ProjectMgmt\\\":true,\\\"Access_SkillPack\\\":true,\\\"Access_FinMgmt\\\":false,\\\"Access_SLA\\\":true,\\\"SLAMgr\\\":false,\\\"AccessType_ServerMon\\\":\\\"No Access\\\",\\\"AccessType_IncidentMgmt\\\":\\\"No Access\\\",\\\"AccessType_CMCMDB\\\":\\\"No Access\\\",\\\"AccessType_CMDB\\\":\\\"\\\",\\\"AccessType_RM\\\":\\\"\\\",\\\"AccessType_KnowledgeMgmt\\\":\\\"\\\",\\\"AccessType_PortfolioMgmt\\\":\\\"\\\",\\\"AccessType_ServiceRequest\\\":\\\"\\\",\\\"AccessType_ServiceCatalog\\\":\\\"\\\",\\\"AccessType_NetworkMon\\\":\\\"No Access\\\",\\\"AccessType_AssetMgmt\\\":\\\"No Access\\\",\\\"AccessType_ProblemMgmt\\\":\\\"No Access\\\",\\\"AccessType_ProjectMgmt\\\":\\\"No Access\\\",\\\"AccessType_SkillPack\\\":\\\"No Access\\\",\\\"AccessType_WorkOrder\\\":\\\"No Access\\\",\\\"AccessType_FinMgmt\\\":\\\"No Access\\\",\\\"AccessType_SLA\\\":\\\"\\\",\\\"Address\\\":\\\"2901 Butterfield Rd\\\\n2nd Flooor\\\",\\\"UserRemarks\\\":\\\"\\\",\\\"State\\\":\\\"\\\",\\\"City\\\":\\\"\\\",\\\"Pin\\\":\\\"\\\",\\\"Active\\\":true,\\\"UT_ID\\\":90,\\\"AccessType_SkillPack1\\\":\\\"No Access\\\",\\\"Access_EProc\\\":true,\\\"AccessType_Eproc\\\":\\\"General Access\\\",\\\"Entity_Access\\\":\\\"\\\",\\\"TimeZone\\\":\\\"(UTC - 06:00) CST - Central Standard Time\\\",\\\"GMT_TimeDiff\\\":-300,\\\"Access_EventMgmt\\\":false,\\\"AccessType_EventMgmt\\\":\\\"No Access\\\",\\\"Keyword_Access\\\":\\\"\\\",\\\"ManagerName\\\":\\\"Arulvelu\\\",\\\"ProjMgmt_InstanceAccess\\\":\\\"\\\",\\\"Manager_UserID\\\":null,\\\"IM_ExtendedRole\\\":\\\"RPT\\\",\\\"AM_ExtendedRole\\\":\\\"RPT\\\",\\\"CustomerMasterID\\\":11,\\\"OrgLogoActive\\\":null,\\\"CustomerLogoActive\\\":null,\\\"AM_EditTemplateID\\\":0,\\\"DesignationID\\\":1381,\\\"PT_userAccessLevel\\\":\\\"Analyst\\\",\\\"PT_workgroupId\\\":0,\\\"PT_CostcentreID\\\":0,\\\"Alternative_EmailID\\\":\\\" , , ,\\\",\\\"ManagerEmailID\\\":null,\\\"ManagerEmployeeID\\\":null}]}}\",\"OutputObject\":null,\"TokenID\":null}",
  "headers": {
    "cache-control": "private",
    "content-type": "application/json; charset=utf-8",
    "server": "Microsoft-IIS/8.5",
    "set-cookie": [
      "ASP.NET_SessionId=2ncl0ezht5; path=/; HttpOnly"
    ],
    "x-aspnet-version": "4.0.30319",
    "x-powered-by": "ASP.NET",
    "date": "Sat, 13 Oct 2018 20:12:39 GMT",
    "connection": "close",
    "content-length": "3314"
  }
}

var responseJSON = JSON.parse(JSON.stringify(responseData));
var responseJSONBody = JSON.parse(responseJSON.body)
var responseJSONBodyOutput = JSON.parse(responseJSONBody.Output)

console.log(responseJSONBodyOutput);

Answer №4

Give this a shot -

body.Output.AllUserDetails['UserDetails '][0].UserID

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

Not all of the data is being retrieved

A form on the page contains two dropdown lists for selecting blood type and city, along with a button. When the button is clicked, information about donors matching the selected blood type and city will be displayed below the form. The postgres database co ...

Global error handling for URQL GraphQL mutation is a critical aspect that needs to be effectively implemented

Here's the technology stack I'm using: react v17.0.2 graphql v16.8.0 graphql-ws v5.14.0 urql v4.0.5 I rely on Hasura Actions to interact with a REST API and am in need of a solution for handling global errors for all mutations. For instance, I ...

Why isn't my JavaScript Alert displaying a string message?

I'm feeling a bit puzzled and I have a feeling there must be an easy solution, so please lend me a hand. Here's the code snippet that is causing me some confusion: $new = "1"; <script language="javascript"> alert(<?php echo $new; ...

JavaScript Time and Date Formatting

I'm pretty new to programming, especially in Javascript. Can someone help me simplify my code? I'm trying to create a dropdown for months and an input field for the year. Is there a more efficient way to make the month select box? Also, how can ...

TypeScript interface with an optional parameter that is treated as a required parameter

Within my interface, I have a property that can be optional. In the constructor, I set default values for this property, which are then overridden by values passed in as the first parameter. If no properties are set, the defaults are used. I am looking fo ...

Combine Rest API with JSON into BPMN for React or Angular 8 along with TypeScript compatibility

Looking for an angular or react BPMN library that supports TypeScript and REST API services without needing to parse XML. I've searched extensively but can't find a BPMN library with JSON service. I need to create a workflow similar to this us ...

Utilize the power of jQuery's AJAX capabilities

Is it normal for a jQuery AJAX request to take between 1-2 seconds before receiving a response? Is there any way to minimize this delay? The response type is JSON and the HTML code is small. Thank you! ...

Select a hyperlink to access the corresponding tab

I've been playing around with bootstrap and AngularJS. I placed nav-tabs inside a modal-window and have it open when clicking on a link. However, I want the appropriate tab to open directly upon click. For example, if I click on "travel", I want the t ...

Steps to include Content-Length in JAX-RS applications

I'm looking to include the size of the JSON in the header of my response. I attempted the following, but it did not work (the response ended up being empty): return Response.ok(OBJECT_MAPPER.writeValueAsString(myObject), MediaType.APPLICATION_JSON).h ...

Sending data from a PHP array to a JavaScript array within a PHP function

I have been scouring Stack Overflow for a solution to my problem, but I haven't found one that fits my specific issue. I recently took over a project from a former coworker that involves managing all the videos and images for my company. My current di ...

D3: Ensuring Map is Scaled Correctly and Oriented Correctly

I am attempting to integrate a map into a website using D3 and topoJSON that resembles the following: https://i.sstatic.net/1brVx.png However, when I create the map with D3/topoJSON, it shows up small and inverted. https://i.sstatic.net/LgQBd.png Even ...

Tips for creating a cohesive group of HTML elements within an editable area

Imagine having a contenteditable area with some existing content: <div contenteditable="true"> <p>first paragraph</p> <p> <img width='63' src='https://developer.cdn.mozilla.net/media/img/mdn-logo-s ...

How to remove the black border on a material-ui button

I am currently working with the material-ui datepicker and buttons. Whenever I click on the datepicker icon to select a date or any of the buttons, I notice a black border appearing. How can I remove this black border from the design? https://i.sstatic.ne ...

Using html data attributes to encode JSON data with strings

Looking for a way to pass data to JavaScript, I decided to create a template tag as shown below: from django.utils.safestring import mark_safe from django import template import json register = template.Library() @register.simple_tag def mydata(): r ...

Having trouble with your mobile dropdown menu not responding to clicks?

I'm having trouble getting a dropdown menu to work on the mobile version of my website. When I click on the dropdown menu image, it's supposed to appear, but it's not working as expected. JSFiddle: https://jsfiddle.net/xfvjv184/ Included ...

What is the reason behind Rxjs switchMap only emitting the final value from an of() observable source?

Here are two code snippets, one using map and the other using switchMap. The functionality of map is clear: of('foo', 'bar') .pipe(map((val) => sanitizer(val))) .subscribe((val) => console.log('value:', val)); func ...

For each JSON object, verify whether the value exceeds zero

How can I iterate through each Json result and check if any of the objects (Stage2) have a value greater than 0, then append it to a div? function service(){ var service_id=document.getElementById('down').value; $.ajax({ &a ...

Transmitting an array through Socket.IO using the emit() method

I am currently developing an array in my socket io server and then transmitting it to the client. var roomList = io.sockets.manager.rooms; // creating a new Array to store the clients per room var clientsPerRoom = new Array(); //for (var i ...

Lambda function to update JSON variables

Is it possible to update each value in a JsonNode tree using a lambda expression? { "resource": { "key1": "value1", "key2": "value2", "key3": "value3" } } Attempting to update the values with the following logic: JsonNode ...

Centering navigation using HTML5

I've been struggling a bit trying to build a website, particularly with centering my <nav> tag. Despite reading numerous suggestions like using CSS properties such as margin: 0 auto; or text-align: center, nothing seems to be working for me. Si ...