Converting JSON to a list using JavaScript

As a beginner in JavaScript, I apologize for asking possibly a redundant question. Can someone guide me on the most effective way to parse json? I am specifically interested in extracting a list of strings under the name Maktg:

{  
   "d":{  
      "results":[  
         {  
            "Maktg":"BATTERY",
            "W":"1000",
            "IS":"",
            "IM":"",
            "IW":"",
            "__metadata":{  
               "type":"s",
               "uri":"https://some_url)"
            },
            "IMaktg":"",
            "Matnr":"0001",
            "Stlan":"1"
         },
         {  
            "Maktg":"CONTROL",
//etc...

Answer №1

Take a look at this JSON structure:

{  
   "d":{  
      "results":[  
         {  
            "Maktg":"LAPTOP",
            "W":"2000",
            "IS":"",
            "IM":"",
            "IW":"",
            "__metadata":{  
               "type":"s",
               "uri":"https://another_url"
            },
            "IMaktg":"",
            "Matnr":"0002",
            "Stlan":"3"
         }
      ]
   }
}

Now, let's transform this JSON string into a JavaScript object for better manipulation:

By using the JSON.parse() method, you can parse a string into JSON format and process the resulting value.

var 
  newJsonStr = '{"d":{"results":[{"Maktg":"LAPTOP","W":"2000","IS":"","IM":"","IW":"","__metadata":{"type":"s","uri":"https://another_url"},"IMaktg":"","Matnr":"0002","Stlan":"3"}]}}';
  newJsonObj = JSON.parse(newJsonStr),
  latestResults = newJsonObj.d.results;

for (var j in latestResults) {

  console.log(latestResults[j]['Maktg']);

  /*
    latestResults[j]['W']
    latestResults[j]['IS']
    latestResults[j]['IM']
    latestResults[j]['__metadata']['type']
    and so on...

  */
}

Answer №2

Give this a shot:

let jsonData = yourData.d.items;
let dataResults = [];
jsonData.forEach(function(item){
    dataResults.push(item.Maktg);
}
console.log(dataResults);

Answer №3

It is recommended to use JSON.parse to retrieve the output in the following manner:

let jsonData = JSON.parse(response);

for(let i=0; i < jsonData.list.length; i++)
{
   console.log(jsonData.list[i].title);
   console.log(jsonData.list[i].description);
   //more code here...
}

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 process for using jQuery to systematically alter the src attribute of all avatar images on Twitter.com?

Summary: I am learning JavaScript and jQuery, and wanted to write a script to replace "_normal.png" with ".png" for all "img.avatar" images on Twitter.com. I encountered an error which I will explain below. Background: Practice makes perfect, so I like to ...

The MVC execution sequence: Controller initialization happening after Ajax call

I'm struggling to understand the execution order in MVC architecture. In my code, I am overriding initialization in the following way: public class HomeController: Controller { protected override void Initialize(RequestContext requestContext) ...

Retrieve an array of items from the Firebase snapshot

Currently in the process of retrieving items from my Firebase database, I am utilizing a snapshot that is generated when the page loads. I have collected the values of each object in an array and I am now attempting to add an item from each object into a s ...

Transform SQL table into JSON Document Store format

Currently, I am utilizing the RaptorDB document store NOSQL database to transition a relational database into a JSON schema document store. The example "Library" database is made up of three tables: CREATE TABLE Book( Book_Id int, Author varchar(255), Tit ...

No information available at the moment

When the data is not present, it displays as "display none"... However, I want it to show "no data found" This is the current code if (a.innerHTML.toUpperCase().indexOf(filter) > -1) { li[i].style.display = ""; } else { li[i].styl ...

Updates to object properties are not appearing in Vue component

I am facing an issue with a Vue component that has a single prop, which is an object. Despite changing a property in this object, it does not reflect the update in the Vue template. Below is a simplified version of the component: <template> <p ...

Eliminate any unnecessary zeros at the end of a number within AngularJS interpolation

Although there are solutions available for plain JavaScript code, unfortunately they are not applicable in this particular scenario. I have a table that needs to be populated with data. The current code snippet is as follows: <tr ng-repeat="rows in $ ...

Understanding the reason why "undefined" is occurring in Javascript

Can anyone help me understand why the alert at the start is showing "undefined"? The alerts are displayed in this order: "success!" "Data" (the correct value) "undefined" I have gone through several threads and found that the issue usually arises du ...

Struggling to grasp the concept of PHP LZW decompression function within JSend framework

I am currently working on converting the LZW decompressor from PHP to JavaScript and I have encountered a function that is giving me some trouble. function decompressLZW(aCodes) { var sData = ''; var oDictionary = []; for (var i = 0; i &l ...

Ways to convert a JavaScript object into restful GET parameters in order to append them to the end of an API URL

Suppose we have a JSON object like this: { name: 'Tony', age: '20', birthday: '20180101', } What is the best way to convert it into parameters that can be appended at the end of a RESTful GET API URL, such as the ...

Guide on counting the number of words in a comma-separated field within a JSON document using Elasticsearch

Here is the JSON data I'm working with: {"index":{"_index":"companydatabase"}} {"FirstName":"ELVA","LastName":"RECHKEMMER","Designation":"CEO","Salary&qu ...

What is the process for updating the header of the group column from "Group" to "my custom heading"?

In my project, I need to replace the header "Group" with "MyCustomHeading". I am implementing this change using treeData in Material UI. ...

Unlock hidden content with a single click using jQuery's click event

I have a question that seems simple, but I can't quite get the syntax right. My issue is with a group of stacked images. When I click on an image, I want it to move to the front and display the correct description above it. Currently, clicking on the ...

Utilizing the power of functional programming with Javascript to perform mapping

In order to address a fundamental issue involving list indexes, I am seeking a functional solution. To illustrate this problem in the context of React and ramda, consider the following example. const R = require('ramda'); const array = ["foo", ...

Resolving the issue of nested modals within Bootstrap

I am experiencing some issues with my customer visits list page. When I try to add a visit, it opens a bootstrap popup ("#Pop1") to record the visit details. Within this modal, there is an option to add a new customer on the spot, which then triggers anoth ...

Is the Three.JS camera update causing issues with the shader?

Attempting to replicate the Bubble shader from https://github.com/stemkoski/stemkoski.github.com/blob/master/Three.js/Bubble.html, but encountering issues due to outdated code. The example should refract whatever is behind it, like this: https://i.sstatic ...

What is the best way to remove an element from a JSON object using Python?

I am currently facing an issue with removing elements from _notes that have _type set to 1. I keep receiving an error message, but I am unsure of its meaning and how to resolve it. Can someone provide assistance? Below is the trimmed JSON: { "_no ...

Utilize React and Django to showcase encoded video frames in your application

Having recently ventured into the world of web development, I've been facing a challenging problem that I can't seem to crack. My tech stack involves the use of React and Django. The issue at hand is with a 3rd party application that utilizes op ...

Echarts: scatter plots linked with a line to the axis (resembling the PACF diagram)

I am currently working with echarts (js). Is there a method to link the dot of the scatter plot with the 0 value on the y-axis? I want it to resemble a pacf plot, similar to this example: The desired outcome should look something like this: https://i.sta ...

Utilizing a Spring Kafka listener to consume JSON data and automatically determine the corresponding domain object

I have a project where I need to process various types of JSON messages that will be published. Unfortunately, I cannot modify the publisher's code to include any headers. However, I am interested in utilizing @KafkaHandler to manage these different J ...