Output the JSON array in JavaScript

I've been struggling to display my JSON response from PHP in the browser console using JavaScript. Despite researching on various websites, I still can't seem to figure it out.

Here's a sample of the JSON data:

{"0":{"codigo_intervencao":"Apoio Emocional - 5270"},"1":{"tempo":"30"},"2":{"codigo_intervencao":"Apoio Emocional - 5270"},"3":{"tempo":"30"},"4":{"codigo_intervencao":"Apoio Emocional - 5270"},"5":{"tempo":"231518"},"6":{"codigo_intervencao":"Apoio Emocional - 5270"}}

My goal is to print each value of the key "codigo_intervencao" in the console, but I haven't been successful so far.

I attempted something like this:

$(document).ready(function() {

  $( "#target" ).click(function() {
    console.log("Select JS");
      $.ajax({
        type: "POST",
        url: "select.php",
        dataType: 'html',
        success: function(response) {
            console.log("Response:" + response); // This prints the JSON data above
            var array = $.parseJSON(response);
            var tempo = 0;
            var arrayLength = array.length;

            for (var i = 0; i < arrayLength; i++) {
              console.log(array[i]['codigo_intervencao']);

        }
      });
  });
}); 

Answer №1

Your data is in JSON format and is not an array.

var data = $.parseJSON(response)
for (item in data){
    console.log(data[item]['intervention_code'])
}

Loop through the JSON data to retrieve the specific element you need.

Answer №2

If you take a look at the JSON example you provided, it would actually be interpreted as an Object. If you want to process it further, you can consider using the following script:

const jsonData = JSON.parse(apiResponse);
const dataArray = Object.keys(jsonData).map(key => jsonData[key]);
dataArray.forEach(element => console.log(element.codigo_intervencao))

For objects without the codigo_intervencao key, you may receive undefined as the output. Another approach could be to iterate through the object using the for..in loop.

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

What is the structure of multi-dimensional arrays in memory?

When working in C, I am aware that I have the ability to dynamically allocate a two-dimensional array on the heap by using the code below: int** someNumbers = malloc(arrayRows*sizeof(int*)); for (i = 0; i < arrayRows; i++) { someNumbers[i] = mallo ...

Linking two socket.io clients together (Establishing a direct socket-to-socket connection that works across different browsers)

Can a direct P2P connection be established between two browsers using socket.io-client, bypassing the node.js server they are currently connected to? If possible, how? The goal is for clients A and B to communicate directly without going through the node. ...

Using Typescript to implement a conditional return type and ensuring that the value types are consistent together

I am working with a useSelectedToggle hook that helps in connecting the UI state to the open/closed status of a dialog where it will be displayed. The toggle defines the value as (T) when it is open, and null when it is closed. How can I enforce stricter ...

Using jQuery to clear a textarea when a select input is changed

Currently, I am in the process of developing a small text editor that enables users to edit files and create new ones. Here is how I have set up my select menu. <select name="reportname" id="reportname" class="form-control"> <option value="zr ...

I am facing an issue with submitting a form using jQuery POST and php serialization

I am struggling to send form data using jQuery. The data seems to be stuck in a loop where it keeps requesting the page ./?page=game&mode=search&type=private with the GET function and does not reach the server. Can someone help me identify what I m ...

How can I adjust the vertical position of Material-UI Popper element using the popper.js library?

https://i.stack.imgur.com/ZUYa4.png Utilizing a material-ui (v 4.9.5) Popper for a pop-out menu similar to the one shown above has been my recent project. The anchorElement is set as the chosen ListItem on the left side. My goal is to have the Popper alig ...

Creating scalable controllers in ExpressJS

Recently diving into Node, I am venturing into the realm of creating an MVC app with ExpressJS. To mimic the structure of a well-known MVC example found on GitHub, I have organized my controllers into two main folders: main and system. My goal is to establ ...

Verify if the array is devoid of elements

Here's the scenario: json_encode($a) = {"p123_04":[]} How can I verify whether it is empty or not? count($a) = int(1) empty((array)$a) = false Are there any other methods I should consider to check if [] is empty or not? ...

Headers cannot be set again after they have been sent to the client in Express Node

I attempted to create a post request for login with the following code: router.post('/login', async(req, res) =>{ const user = await User.findOne({gmail: req.body.gmail}) !user && res.status(404).json("user not matched") c ...

Refreshing Slickgrid: Updating grid data with data fetched from an AJAX source

Within the app I am developing, there exists a data grid alongside select boxes that allow users to set filters. Upon selection of these filters, an AJAX call is made to retrieve a new array of data from the server. The challenge I currently face is wipin ...

experiencing an excessive amount of re-renders after transferring data to a distinct component

At the moment, I have implemented this logic to display data based on the results of a graphql query, and it is working well: const contacts = () => { const { loading, error, data } = useUsersQuery({ variables: { where: { id: 1 }, ...

Utilize VueJS to pass back iteration values using a custom node extension

Hey there! I'm currently working on a Vue app that generates a color palette based on a key color. The palette consists of 2 lighter shades and 2 darker shades of the key color. To achieve this, I have set up an input field where users can enter a hex ...

HTML5 allows users to choose data from a list using a ComboBox and submit the 3-digit code

I'm looking to enhance my form by including an input box where users can select airports, similar to the functionality on this website (). When typing in the Destination Input, I want users to see a list of possible values with detailed suggestions su ...

Prevent anchor jumping caused by popstate event in Safari

This situation is really testing my patience. When navigating within the same page using anchors, the browser automatically takes you back/forward to the location of that link in your history when popstate is triggered. One might think that you could prev ...

Activate the audit command for the npm enterprise registry

I'd like to know how to activate the npm audit command in my npm enterprise registry. Whenever I attempt to run the npm audit command, I encounter the following error: { "error": { "code": "ENOAUDIT", "summary": "Your configured registry ( ...

Is there a way to bring together scrolling effects and mouse movement for a dynamic user

If you want to see a scrolling effect, check out this link here. For another animation on mouse move, click on this link(here). Combining both the scrolling effect and the image movement might seem challenging due to different styles used in each templat ...

Choosing a default selection in a nested v-for loop for a select box

Currently, I have a list of items that users can add new items to. Each item is required to have a select box, and the selected value from the select box should be assigned as the item's value. In an attempt to bind the select box to the item using t ...

Rewriting URLs in Angular 2

I am a beginner in Angular 2 and I am currently working on a project that requires URL rewriting similar to that of ' '. In Zomato, when you select a city, the city name appears in the URL like ' ', and when you select a restaurant, t ...

Error encountered while trying to retrieve the response

Currently, I am in the process of developing a script that utilizes node.js, fbgraph API, and the express framework. My task involves sending the user's access_token from an index.html page to the nodejs server via a POST request. I have successfully ...

What is the best way to retrieve the nearest form data with jQuery after a child input has been modified?

I have a page with multiple forms, each containing several input checkboxes. When one of the form inputs changes, I want to gather all the parent form's data into a JSON array so that I can post it elsewhere. I'm having trouble putting the post ...