How to process and handle a JSON response containing multiple objects using JavaScript

I received a JSON response that looks something like this.

{
   returnCode: 'Success',
   info: null,
   result: {
       payload: '{
            "BatchNo":"143123",
            "Supplier":"Automotive",
            "ItemNumber":"AP123",
            "ProdNumber":"\\"\\"",
            "ItemIdentifier":"PROCURE"}             
            {
            "BatchNo":"143123",
            "Supplier":"Manufacturing",
            "ItemNumber":"API124",
            "ProdNumber":"PRD123",
            "ItemIdentifier":"PRODUCE"}',
 encode: 'UTF-8'
 },
  txid:'8d9efd6083e6ca737e9c751baecd0c75cf738e9ce0e599bcfa26910575fa6d5f8d9efd6083e'
}

I am trying to figure out how to access the result.payload.ItemNumber values without using arrays in the JSON data. Is there anyone who can assist me with this so I can display the following output?

AP123
AP124

I attempted the code below, but it did not work. Can someone please provide guidance?

 var output1 = JSON.parse(json).result.payload[1].ItemNumber;
 console.log("Data:"+ output1);

Thank you.

Answer №1

Important Message

After some necessary adjustments, the payload has been cleaned up and transformed into an array containing a list of objects separated by commas. This was essential to ensure that the response data remains valid.

Programming Snippet

let json = {
   returnCode: 'Success',
   info: null,
   result: {
       payload: '[{"BatchNo":"143123","Supplier":"Automotive","ItemNumber":"AP123","ProdNumber":"\\"\\"","ItemIdentifier":"PROCURE"},{"BatchNo":"143123","Supplier":"Manufacturing","ItemNumber":"API124","ProdNumber":"PRD123","ItemIdentifier":"PRODUCE"}]',
        encode: 'UTF-8'
 },
  txid:'8d9efd6083e6ca737e9c751baecd0c75cf738e9ce0e599bcfa26910575fa6d5f8d9efd6083e'
}

 var output1 = JSON.parse(json.result.payload)[1].ItemNumber;
 console.log("Data:"+ output1);

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

Sending an HTTP POST request from Angular 4 to Java SpringMVC results in the issue of POST parameters not

Currently, I am developing a REST API using Java Maven Spring Boot and Spring MVC. I have encountered an issue where Angular POST request parameters are not being recognized by SpringMVC's @RequestParam. Below is the Angular code snippet; saveAsSit ...

Executing a method from the parent controller within nested directives by utilizing isolated scope

I need help with a treeview directive in my project. I am having trouble invoking a function from the parent controller and can't seem to figure out why it's not working. It could be due to the structure of the treeview and nesting of child eleme ...

Can someone assist me in retrieving the current date from the epoch? I am currently receiving the date as January 19, 1970

Obtain the review date from a JSON object and format it: String datetime = jsonObject.getString("ReviewDate"); datetime = datetime.replace("Date(", "").replace(")", "").replaceAll("/", ""); Long ldate = Long.valueOf(datetime); Date date ...

Tips for swapping out a page for a component

Consider a scenario where we have a blog page containing a div element with the class "content" that displays previews of various articles. The goal is to dynamically replace the content within the div element with a specific article. How can this be acco ...

Guide on printing in an Ionic application using print.js without the need to open the printer setup page

Our team is currently working on an Ionic web application that utilizes printer functionality. To enable printing, we have integrated the Print.js npm package. However, when we initiate the print method, a setup page displaying details such as printer na ...

Is there a way to determine the distance in miles and feet between various sets of latitude and longitude coordinates?

I am working with an array of latitude and longitude coordinates and I am looking to use JavaScript or Typescript to calculate the distance in miles and feet between these points. const latsLngs = [ { lat: 40.78340415946297, lng: -73.971427388 ...

Turning HTML into an image with the power of JavaScript

Utilizing html2canvas to convert a div into an image, everything is functioning properly except for the Google font effect. The image shows how it eliminates the effect from the text. https://i.stack.imgur.com/k0Ln9.png Here is the code that I am using f ...

There seems to be an issue with the package not running at xxx:yy in React

As I work on developing a standalone Android app using React Native, the installation of react-native-fcm has led to a persistent error message appearing: The Gradle file in my project appears as follows: // Top-level build file where you can add configu ...

Using JavaScript to utilize a variable containing a .match method with Regex Expression

Recently, I started delving into the world of regex with the aim of incorporating variables in my matches. Imagine I have a string that reads "Total: $168" My goal is to extract just the numerical value; 168. This is what I currently have: totalCost = t ...

Organizing the Outcomes of an Array

After a successful ajax request, I receive an array that contains information about various locations. Here is how the array looks: List of Locations: [{ "locationID": "9", "locationName": "Employee Residenc ...

Deliver data in batches of ten when the endpoint is accessed

I am currently in the process of developing a web application using Next.JS and Node. As part of this project, I have created my own API with Node that is being requested by Next.JS. One particular endpoint within my API sends data to the front end as an ...

Error message: Unable to access properties of null when calling 'registerPlugin' in @devexpress/dx-react-grid-material-ui

I have developed a CustomGrid component that is based on the DevExpress Grid component. So far, it has been working smoothly. Here's how the implementation looks like in App.tsx: import Paper from "@mui/material/Paper"; import { Table, TableHeaderRow ...

Ways to transform date into a different structure using JavaScript

Fetching a date from an API gives me this format: 2017-04-20T07:00:00Z How can I convert it to the following format? 20.04.2017 I am using React to render the date: <div>{props.data.day}</div> I attempted to use toISOString().slice(0, 1 ...

Using multiple `setState` calls without synchronization can lead to issues, especially when one of them uses a value obtained from `

In my discovery: When there are two instances of setState The first one is invoked with a value obtained from await Both calls occur in the same thread It results in a scenario where one state is updated while the other remains unchanged. For instance: ...

Transferring Session ID between Express.js and Socket.io while dealing with iframes from distinct origins

My Node application built with Express.js and Socket.io is facing an issue where they are not sharing the same session ID when running under iframe with different origins. When accessed directly or through iframes with the same origin, everything works fin ...

What is the best way to pass a prop into the <router-link>?

If I replace this {{ name }}, the result is "campaigns" Now, I want to use that in my link <router-link :to="'/' + '123' + '/' + item.id"> {{ item.name }}</router-link> I attempted to substitute '1 ...

Creating a straightforward Theme Changer feature using Vue.js

Check out this tutorial for creating a simple Dark/Light theme switcher using Tailwind CSS. This tutorial utilizes vanilla JS and only requires a single app.js file. If I want to incorporate this into a Vue project, should I simply paste the code into ~/s ...

Information gathered from checkboxes and dropdown menus

When gathering information from my form fields, I know how to capture data from input fields using this code: 'formData' : { 'timestamp' : '<?php echo $timestamp;?>', 'token' : '<?php echo md5(&a ...

The challenge of solving mazes with recursion

Imagine a 2D character array filled with 0's and 1's, where 0 signifies a wall and 1 represents a valid path. In order to locate the exit marked with an 'x' in this maze, I have created a recursive function called findPath(int r, int c) ...

Ways to generate an array containing the headings from a list using typescript?

How can I extract the headers of objects in an array in TypeScript? let data = [{name: "A", skills: 50, result: 80}, {name: "B", skills: 40, result: 90}, {name: "C", skills: 60, result: 60}]; let headers = Ob ...