Ganesh Babu
Ganesh Babu

Reputation: 3670

How to extract Array from JSON in $.ajax response

I have a json value converted from array in ajax response.

{"Text":"Please provide a value","Email":"Please provide a value"}

I need the response json to be extracted in a div using $(div).html():

Text-Please provide a value
Email-Please provide a value

I tried it using $.each():

var json=JSON.stringify({"Text":"Please provide a value","Email":"Please provide a value"});
    var arr = [];
    var obj = jQuery.parseJSON(json);
    $.each(json,function(key,value)
    {
     arr.push('<li>'+value+'</li>');
    });
    var arrval =arr.join('');
    console.log(arrval);

But I got output as undefined. I know there is some logical mistake I have done while extracting? What have I done wrong in here??

Note: The array key value pair in json can be dynamic ie., it may be one, two or more..

Upvotes: 0

Views: 14977

Answers (4)

user2660730
user2660730

Reputation: 44

I think this might be helpful

var  json = {"Text":"Please provide a value","Email":"Please provide a value"};
var arr = [];
$.each(json,function(key,value){
    arr.push('<li>'+value+'</li>');
});
var arrval =arr.join('');
console.log(arrval);

Upvotes: 1

Dawit
Dawit

Reputation: 11

json is an array of objects, thus has a length property that you can use to iterate its elements.

var result;

for(var i=0;i<json.data.length;i++)
{
      result += json.data[i].text+ ', ';
}

Most debugger consoles support displaying objects directly. Just check your result using

console.log(obj);

Upvotes: 0

asharajay
asharajay

Reputation: 1193

see this if it helps !!

var jsonData = {"Text":"Please provide a value","Email":"Please provide a value"};
var arr = [];
for(var j in jsonData){
    var sub_key = j;
    var sub_val = eval("jsonData."+j);
    arr.push('<li>'+sub_key+": "+sub_val+'</li>');    
}

Upvotes: 1

Jacky Lormoz
Jacky Lormoz

Reputation: 165

$(obj).each(function(index,value)
{
  arr.push('<li>'+value.Text+'</li>');
});

your json have to look like:

[{"Text":"Please provide a value","Email":"Please provide a value"}]

Upvotes: 0

Related Questions