0

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..

2
  • 6
    You are iterating over the original string. You should write $.each(obj, ...) instead of $.each(json, ...). Commented Sep 12, 2013 at 9:07
  • @FrédéricHamidi Thanks for showing correct way. Your suggestion worked... Commented Sep 12, 2013 at 9:18

4 Answers 4

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

I thought calling $.parseJSON() on json (json to object conversion) and then $.makeArray() on the result (object to array conversion) would get me the array I wanted, but my $.parseJSON() resulted a null. Any pointers?
1

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>');    
}

Comments

0
$(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"}]

Comments

0

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);

1 Comment

How exactly does that fit the question? Please edit to improve.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.