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

Is there a way to customize the checkout page using JavaScript?

I'm working on a checkout page where fields need to change based on a selected radio button. There are two options: A and B. When A is selected, I want certain fields to remain visible while others disappear, and vice versa for option B. Although I p ...

Magnify novice mistakes: Unhandled promise rejection and Ensure every child has a distinct "key" property

Currently, I am working through Amazon's Getting Started with AWS tutorial found here: https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/module-four/ After successfully building and hosting the app on git, I noticed that ...

How can React and Redux ensure that response data is accessible to every component?

When using react and redux, how can data written in the useDispatch function be made available in other components? Additionally, how can the customerId be accessed in all components? I have created a code that calls an API and returns data in response. I ...

Issues arise when attempting to transfer strings through ajax to a Node.js server that is utilizing express.js

On my website, I am encountering a problem where certain characters are being lost when I send strings to my Node.js server. // Client: microAjax("/foo?test="+encodeURI("this is ++ a test"), function callback(){}); // Server: app.get('/foo',fun ...

Is there a way to display an alert using JavaScript that only appears once per day?

I've created a website that displays an alert to the user upon logging in. Currently, the alert is shown each time the user logs in, but I'm looking to make it display only once per day at initial page loading. How can I achieve this? Below i ...

AngularJS is behaving in a way that requests fresh JSON data only during the initial loading

I'm currently utilizing AngularJS to incorporate an app into a native iOS application, but I'm encountering difficulties with loading dynamic data. I have configured the controllers to retrieve JSON data from the iOS app via http queries for eac ...

What is the best way to recycle Vue and Vuetify code?

<script> export default { data () { return { my_alert: false, text: '', color: 'success' } }, methods: { openAlt (text, color) { this.text = text this.color = color this.my_ale ...

Steps to transfer selected autocomplete value ID to data attribute using jQuery

I am working on a project where I need to store the State ID in my database instead of the State Name. Currently, I am using an autocomplete query to select the State. How can I pass the selected State's respective ID to the data-attribute of the inpu ...

What is the best way to halt a jQuery function when hovering over it?

Currently, I have a jQuery function set up to run on setInterval(). However, I am looking for a way to pause the interval when hovering over the displayed div and then resume once no longer hovering (i.e., continue cycling through the divs). Does anyone ...

An error is thrown when using AngularJS .length property

Currently, I am carrying out a regular task within my Filter to verify if angular.module('someApp') .filter('filterSomeData',['$filter',function ($filter) { return function (items, keyObj) { var filterObj ...

Testing the number of times module functions are called using Jest

As someone who is relatively new to JavaScript and Jest, I am faced with a particular challenge in my testing. jest.mock('./db' , ()=>{ saveProduct: (product)=>{ //someLogic return }, updateProduct: (product)=>{ ...

Properly aligning text with checkboxes using HTML/CSS and tags like <span> or <div>

My goal is to have the text displayed as a block in alignment with the checkbox, adjusting based on the sidebar's width. For reference: Current Layout Preferred Layout I have shared the code on CodePen (taking into account screen resolution and wi ...

What is the best way to retrieve a JSON string in JavaScript after making a jQuery AJAX request?

Why am I only seeing {} in the console log when ajax calling my user.php file? $.ajax({ url: '.../models/user.php', type: 'POST', dataType: "json", data: {username: username, password:password, func:func}, succ ...

Exploring Kotlin to retrieve information from Json fetch results

I am retrieving JSON data from this URL using OKhttp. My coding language of choice is Kotlin. { "CountryName": [{ "Country": "India", "CountryCode": "+91", "Population": "545121546846" }, { "country ": "Pakistan", ...

Is there a feature in JavaScript that allows for the creation of URLs?

I created an index view displaying cards (like playing cards) in a grid using BootStrap. Each card is within its own div element, and I implemented a jQuery click handler for each div to open a details page when clicked. The redirect from the index to the ...

Using Selenium Webdriver to target and trigger an onclick event through a CSS selector on a flight booking

I've been running an automation test on the website . When searching for a flight, I encountered an issue where I was unable to click on a particular flight. I initially tried using Xpath but it wasn't able to locate the element when it was at th ...

E6 arrow functions simplify the process of condensing an array of objects into a single object

Here is an array that I have: a=[{'test':1,'test2':'2'},{'test':3,'test2':'4'}] My goal is to reduce this array into a single object This is the expected output {1:2,3:4} I attempted the foll ...

Setting a variable in Angular after a successful AJAX call

Working on a new small application and experimenting with Angular. Encountering an issue where I am making an AJAX GET request upon clicking a button. After receiving the response, I want to set a variable to hold the result, but for some reason the variab ...

Exploring Tabletop.js to retrieve information from an array of data

Issue I am currently attempting to retrieve data from an array that contains two objects. I have implemented Tabletop.js to fetch the data from a public Google Spreadsheet, but I encountered an error in the console stating ReferenceError: object is not de ...

Executing Knex promises sequentially within a for loop

I have recently started to dive into Node and asynchronous coding, but I am struggling with a fundamental concept. I am trying to seed a database using knex, reading data from a CSV file and iterating through the rows in a for loop. In each iteration, I ne ...