Extract information from a string to retrieve the array specifications

After making a request to the server, I received the following response:

{
  "statusCode": 200,
  "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F106457749C\",\"OrgID\":0,\"OutputObject\":{\"Details\":{\"CatalogDetail\":[{\"CatalogID\":74,\"CategoryID\":22,\"ShortCatalogName\":\"Email Forwarding\",\"CatalogName\":\"Email Forwarding\",\"Description\":\"Use this catalog for email forwarding \",\"IsVendor\":false,\"IsPackage\":false,\"AncestorParent_CategoryID\":58,\"IsEntitled\":0,\"CategoryName\":\"Email\",\"ServiceCatalogBGColor\":\"\"}],\"BaseUrl\":\"https://serviceimg-attachments\"}}}",
  "headers": {
    "cache-control": "private",
    "content-type": "application/octet-stream",
    "server": "Microsoft-IIS/8.5",
    "set-cookie": [
      "ASP.NET_SessionId=m0jbtyi12mzefkkyh3xd4i0m; path=/; HttpOnly",
      ".ASPXAUTH=41C6BC3E87DBF106457749C; path=/"
    ],
    "x-aspnet-version": "4.0.30319",
    "x-powered-by": "ASP.NET",
    "date": "Mon, 15 Oct 2018 17:51:09 GMT",
    "connection": "close",
    "content-length": "779"
  }
}

I am attempting to parse the string response.body in order to retrieve the array

response.body.OutputObject.Details.CatalogDetail
. However, I am encountering an issue where Details is undefined. Could someone provide guidance on how to access the CatalogDetail Array?

Thank you, Arul

Answer №1

Here is a suggestion for you:

You can parse the JSON string like this:
var jsonObj = JSON.parse("your json string");

Answer №2

In order to access the object, it is necessary to first parse the JSON data. The JSON.parse method can be used to parse the JSON string.

var jsonData = '{"success":true, "quantity":10}';
var obj = JSON.parse(jsonData);

Answer №3

This is the method I've been using and it's effective. Instead of trying to parse the entire object at once, extract the body object first.

var body = JSON.parse(data["response"])

After that, you can access the specific details like this.

JSON.parse(data["response"]).OutputObject.Details.CatalogDetail

Answer №4

To properly read the content, it is necessary to interpret the body as JSON data. Most likely, the framework being utilized offers a method similar to response.json(), but alternatively, you can employ JSON.parse.

response = {
  "statusCode": 200,
  "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F106457749C\",\"OrgID\":0,\"OutputObject\":{\"Details\":{\"CatalogDetail\":[{\"CatalogID\":74,\"CategoryID\":22,\"ShortCatalogName\":\"Email Forwarding\",\"CatalogName\":\"Email Forwarding\",\"Description\":\"Use this catalog for email forwarding \",\"IsVendor\":false,\"IsPackage\":false,\"AncestorParent_CategoryID\":58,\"IsEntitled\":0,\"CategoryName\":\"Email\",\"ServiceCatalogBGColor\":\"\"}],\"BaseUrl\":\"https://serviceimg-attachments\"}}}",
  "headers": {
    "cache-control": "private",
    "content-type": "application/octet-stream",
    "server": "Microsoft-IIS/8.5",
    "set-cookie": [
      "ASP.NET_SessionId=m0jbtyi12mzefkkyh3xd4i0m; path=/; HttpOnly",
      ".ASPXAUTH=41C6BC3E87DBF106457749C; path=/"
    ],
    "x-aspnet-version": "4.0.30319",
    "x-powered-by": "ASP.NET",
    "date": "Mon, 15 Oct 2018 17:51:09 GMT",
    "connection": "close",
    "content-length": "779"
  }
}
body = JSON.parse(response.body)
body.OutputObject.Details.CatalogDetail

Answer №5

Use JSON.parse(data.body) to convert the string into JSON format and perform any desired operations,

Learn More about JSON.parse

Here is a code snippet for reference:

var data = {
  "statusCode": 200,
  "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F106457749C\",\"OrgID\":0,\"OutputObject\":{\"Details\":{\"CatalogDetail\":[{\"CatalogID\":74,\"CategoryID\":22,\"ShortCatalogName\":\"Email Forwarding\",\"CatalogName\":\"Email Forwarding\",\"Description\":\"Use this catalog for email forwarding \",\"IsVendor\":false,\"IsPackage\":false,\"AncestorParent_CategoryID\":58,\"IsEntitled\":0,\"CategoryName\":\"Email\",\"ServiceCatalogBGColor\":\"\"}],\"BaseUrl\":\"https://serviceimg-attachments\"}}}",
  "headers": {
    "cache-control": "private",
    "content-type": "application/octet-stream",
    "server": "Microsoft-IIS/8.5",
    "set-cookie": [
      "ASP.NET_SessionId=m0jbtyi12mzefkkyh3xd4i0m; path=/; HttpOnly",
      ".ASPXAUTH=41C6BC3E87DBF106457749C; path=/"
    ],
    "x-aspnet-version": "4.0.30319",
    "x-powered-by": "ASP.NET",
    "date": "Mon, 15 Oct 2018 17:51:09 GMT",
    "connection": "close",
    "content-length": "779"
  }
};
var output = JSON.parse(data.body);
console.log(output.OutputObject.Details.CatalogDetail);

Answer №6

To access specific properties, use JSON.parse and refer to the documentation on Property Accessors.

  var obj = {
      "statusCode": 200,
      "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F106457749C\",\"OrgID\":0,\"OutputObject\":{\"Details\":{\"CatalogDetail\":[{\"CatalogID\":74,\"CategoryID\":22,\"ShortCatalogName\":\"Email Forwarding\",\"CatalogName\":\"Email Forwarding\",\"Description\":\"Use this catalog for email forwarding \",\"IsVendor\":false,\"IsPackage\":false,\"AncestorParent_CategoryID\":58,\"IsEntitled\":0,\"CategoryName\":\"Email\",\"ServiceCatalogBGColor\":\"\"}],\"BaseUrl\":\"https://serviceimg-attachments\"}}}",
      "headers": {
        "cache-control": "private",
        "content-type": "application/octet-stream",
        "server": "Microsoft-IIS/8.5",
        "set-cookie": [
          "ASP.NET_SessionId=m0jbtyi12mzefkkyh3xd4i0m; path=/; HttpOnly",
          ".ASPXAUTH=41C6BC3E87DBF106457749C; path=/"
        ],
        "x-aspnet-version": "4.0.30319",
        "x-powered-by": "ASP.NET",
        "date": "Mon, 15 Oct 2018 17:51:09 GMT",
        "connection": "close",
        "content-length": "779"
      }
    }

    var formated = JSON.parse(obj.body);

    var CatalogDetail = formated.OutputObject.Details.CatalogDetail[0];
    console.log(CatalogDetail);

Answer №7

the reason for this issue is that the body's value is in string format. If you want to access it as a JSON format, you will need to parse it first. Below is a code snippet for more clarification:

var response = {
  "statusCode": 200,
  "body": "{\"Errors\":\"\",\"Message\":\"\",\"Output\":\"\",\"TokenID\":\"F106457749C\",\"OrgID\":0,\"OutputObject\":{\"Details\":{\"CatalogDetail\":[{\"CatalogID\":74,\"CategoryID\":22,\"ShortCatalogName\":\"Email Forwarding\",\"CatalogName\":\"Email Forwarding\",\"Description\":\"Use this catalog for email forwarding \",\"IsVendor\":false,\"IsPackage\":false,\"AncestorParent_CategoryID\":58,\"IsEntitled\":0,\"CategoryName\":\"Email\",\"ServiceCatalogBGColor\":\"\"},{\"CatalogID\":75,\"CategoryID\":22,\"ShortCatalogName\":\"Email Forwarding2\",\"CatalogName\":\"Email Forwarding2\",\"Description\":\"Use this catalog for email forwarding \",\"IsVendor\":false,\"IsPackage\":false,\"AncestorParent_CategoryID\":58,\"IsEntitled\":0,\"CategoryName\":\"Email\",\"ServiceCatalogBGColor\":\"\"}],\"BaseUrl\":\"https://serviceimg-attachments\"}}}",
  "headers": {
    "cache-control": "private",
    "content-type": "application/octet-stream",
    "server": "Microsoft-IIS/8.5",
    "set-cookie": [
      "ASP.NET_SessionId=m0jbtyi12mzefkkyh3xd4i0m; path=/; HttpOnly",
      ".ASPXAUTH=41C6BC3E87DBF106457749C; path=/"
    ],
    "x-aspnet-version": "4.0.30319",
    "x-powered-by": "ASP.NET",
    "date": "Mon, 15 Oct 2018 17:51:09 GMT",
    "connection": "close",
    "content-length": "779"
  }
}
var body = JSON.parse(response.body)
var Catalogs = body.OutputObject.Details.CatalogDetail;
for(var i=0;i<Catalogs.length;i++){
    console.log("CatalogID : " + Catalogs[i].CatalogID)
    console.log("ShortCatalogName : " + Catalogs[i].ShortCatalogName);
}
$.each(Catalogs, function( index, value ) {
  console.log(  "CatalogID : " + value.CatalogID );  
  console.log(  "ShortCatalogName : " + value.ShortCatalogName );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
you can utilize either a simple for loop or $.each loop to iterate through the array

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

jQuery: Set default option selected or reset value

I'm attempting to change the value of the nearest select option dynamically. $(document).ready(function () { $('.limitation_points').hide(); $('.field .limitSelected').each(function () { $(this).change(function ( ...

determining the position of the substring located within an "if any" function

I have two lists A and B. My goal is to extract a string from list A, find a matching string in list B, and then determine the index of that matching string in list B. I've attempted several nested loops without success. I haven't come across an ...

JavaScript can be utilized to eliminate bootstrap tooltip attributes

Having trouble with adding and removing bootstrap tooltip attributes using JavaScript. The tooltip is added on mouseover, but not removed on mouseleave. The script adds the tooltip attributes on mouseover and should remove them on mouseleave. 'use s ...

Unable to set a value of type 'String?' to a variable of type 'String?.Type'

Having trouble resolving this error: Here is the code snippet causing it: func setInfo(json: JSON) { self.name = json["name"].string self.email = json["email"].string let image = json["picture"].dictionary let imageData = image?["data"]? ...

Provide JSON data on a designated pathway

I'm currently working on setting up a basic API that will respond with JSON data when accessed at the path /json The goal is to send back the object {"message": "Hello json"} in JSON format whenever a GET request is made to the /j ...

Received an error while attempting an AJAX GET request to a distinct server hosting a WebAPI

This is my first time encountering an issue with an Ajax request in client-side code. I'm hoping that there's a simple mistake in my code that I'm just overlooking. Just to give some background, when I manually access the URL mentioned below ...

What is the best way to organize code into separate files while utilizing a module that needs to be included in every file?

In this particular scenario, I am utilizing a headless browser with Puppeteer Chrome and MongoDB. Take a look at the following code snippet: var browser = await puppeteer.launch() var page = await browser.newPage() var db = await MongoClient.connect(" ...

"Using Angular's NgFor directive to efficiently organize and collapse data within

I am currently working on displaying API data in a table using ngFor, and I am facing an issue with hiding/showing a specific row of details outside the ngFor loop. Since this line is not within the ngFor loop, I am unable to bind the data accordingly. Can ...

Utilizing Vue.js 2 to dynamically update data through directives

Is it possible to change a data property from a directive using single file components? For instance, consider the following code... export default { name: 'app', data: function() { return { is_loading: true ...

Steering clear of Unique error E11000 through efficient handling with Promise.all

In my development work, I have been utilizing a mongoose plugin for the common task of performing a findOrCreate operation. However, I recently discovered that running multiple asynchronous findOrCreate operations can easily result in an E11000 duplicate k ...

Converting image bytes to base64 in React Native: A step-by-step guide

When requesting the product image from the backend, I want to show it to the user. The issue is: the API response contains a PNG image if the product has an image, but returns a (204 NO Content) if the product does not have an image. So, I need to display ...

Create a global variable by importing an external module in TypeScript

I am currently developing a TypeScript npm module called https://www.npmjs.com/package/html2commonmark. This module is versatile and can be utilized in nodejs (via require) as well as in the browser (by loading node_modules/html2commonmark/dist/client/bund ...

Modify Twig template variable using AJAX

I'm attempting to dynamically reload a section of my HTML with new data fetched through AJAX. Within the code, there is a loop that iterates over clients: {% for client in clients %} After making an AJAX request and receiving updated client informa ...

Validating Password Consistency using Javascript

I'm having trouble with validating the password fields and ensuring they match, even when both input boxes contain the same password. JavaScript var validator = $("#signupform").validate({ rules: { password: { required: true, minle ...

What is the best way to retrieve an ng-model parameter within a controller?

I'm working on implementing a PUT method in my controller and need to bind the new value back to it. I've tried: <div ng-app="myApp" ng-controller="personCtrl"> <form> First Name: <input type="text" ng-mod ...

Rotating an HTML caret using CSS does not pivot from the center point

Is there a way to adjust my simple caret rotation to make it rotate from the center? What changes should I make? const Wrap = styled.div` width: 100px; background: grey; span { display: block; transform: ${(props) => (props.isOpen ? " ...

What is the process for selecting and clicking a specific div with a distinct class name in HTML

Hey there! I'm a beginner at coding with puppeteer and I have a question. How can I make my code click on this image: (image) The current code I have looks like this: const puppeteer = require('puppeteer'); (async () => { const bro ...

Changing the size of a responsive navigation bar with React and adjusting it based on the window.scrollY position switches between collapsed and un

I'm struggling to create a responsive navbar that automatically adjusts its size once it surpasses the height of the navbar (currently set at 80px). However, when I scroll to around the 80px mark, it starts flickering between the collapsed and expande ...

Passing a variable from the server to the client function in Meteor with a delay

When I invoke a server function from the client side, it executes a UNIX command and retrieves the output on the server. However, I face an issue where the result is immediately returned as undefined by Meteor.call because the exec command takes some time ...

Trigger a unique event using Vanilla JS and then detect it on Vue instances

I am currently in the process of incorporating multiple Vue instances into my website. I have encountered issues preventing me from making the entire website a Vue instance and using components due to potential conflicts and other complications. For examp ...