Rudziankoŭ
Rudziankoŭ

Reputation: 11251

Javascript: parse json to list

I am new to javascript, sorry for silly question and possible duplicate. Please suggest me efficient way of parsing json. I would like to fetch list of strings 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...

Upvotes: 1

Views: 1612

Answers (3)

Ali Mamedov
Ali Mamedov

Reputation: 5256

We have a JSON:

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

Lest convert string JSON into more useful JavaScript object:

The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.

var 
  jsonStr = '{"d":{"results":[{"Maktg":"BATTERY","W":"1000","IS":"","IM":"","IW":"","__metadata":{"type":"s","uri":"https://some_url"},"IMaktg":"","Matnr":"0001","Stlan":"1"}]}}';
  jsonObj = JSON.parse(jsonStr),
  results = jsonObj.d.results;

for (var i in results) {

  console.log(results[i]['Maktg']);

  /*
    results[i]['W']
    results[i]['IS']
    results[i]['IM']
    results[i]['__metadata']['type']
    and etc...

  */
}

Upvotes: 1

Kirankumar Dafda
Kirankumar Dafda

Reputation: 2384

Please try to get output with JSON.parse like this.

var getData = JSON.parse(data);

for(i=0;i<getData.d["results"].length;i++)
{
   alert(getData.d["results"][i].Maktg);
   alert(getData.d["results"][i].W);
   //etc...
}

Upvotes: 0

Amresh Venugopal
Amresh Venugopal

Reputation: 9549

Try this:

var jsonArray = yourJSON.d.results;
var results = [];
jsonArray.forEach(function(object){
    results.push(object.Maktg);
}
console.log(results);

Upvotes: 1

Related Questions