How to read json response as pairs of name values โ€‹โ€‹in jQuery

I want to read json response as name and value pairs in my jQuery code. Here is my example JSON response that I am returning from my java code:

String jsonResponse = "{"name1":"value1", "name2:value2"}; 

in my jQuery, if I write jsonResponse.name1 , I will get the value as "value1" . Here is my jQuery code

 $.ajax({ type: 'POST', dataType:'json', url: 'http://localhost:8080/calculate', data: request, success: function(responseData) { alert(responseData.name1); }, error: function(XMLHttpRequest, textStatus, errorThrown) { //TODO } }); 

Here I want to read "name1" from jsonResponse instead of hardcoding in jQuery. Something like a loop to get an answer, getting every name and value. Any suggestions?

+7
json jquery getjson
source share
3 answers
 success: function(responseData) { for (var key in responseData) { alert(responseData[key]); } } 

It is important to note that the order in which properties will be executed is arbitrary and cannot be relied on.

+12
source share

You can simply use responseData['name1'] . Easy.

+5
source share

This is easy:

 json = {"key1": "value1", "key2": "value2" }; $.each(json, function(key, value) { alert(key + "=" + value); }); 
+5
source share

All Articles