Collapsible Java map is returned as JSON response using javascript

I did not find a specific answer that addresses the following question.

I have the following JSON response received through an AJAX POST request.

{ "result": { "101010":["PRAVAT","SGSGSG","UKEMP5","UKENTD","WAUK01","MK87UK"], "202020":["CORA1E","PSASAS","EDCRJS","USHC01","USDR06"], ............................ ........................ "304050":["ERCDE2","DELT01","DECGKG","DEHC03","IS02","DEPI01"] }, "status":"SUCCESS" } 

I want to display data above data using a loop in javascript. I tried for ( var i = 0; i < response.result.length; i++) { but I cannot do this.

Please help me parse and display my data in the above JSON format using javascript.

+4
source share
4 answers

You have an object, not an array. Only arrays have the length property. To iterate on using an object:

 $.post("yoururlhere", function(JSONData) { var obj = $.parseJSON(JSONData); if (obj.status.toLowerCase() === "success") { for (var key in obj.result) { if (obj.result.hasOwnProperty(key)) { console.log(key + ': ' + obj.result[key]); } } } }); 

The value if (obj.result.hasOwnProperty (key)) forces you to ignore the properties of the prototype. If you want to view it, this is a tool that you can inherit in Javascript.

+3
source

Do you have this as an object or JSON?

To convert JSON to an object in jquery, use $.parseJSON() .

EG. var obj = $.parseJSON(myJSONData);

Once you have an object, you can scroll through the keys using:

 for (var key in obj) { console.log(key + ': ' + obj[key]); } 
+4
source

You have to JSON.parse() it, you can use JSON.parse() or jQuery.parseJSON() . Look at this: JSON parsing in JavaScript?

+1
source

As MostafaR said, you need to parse it into a javascript object first. When you get JSON from somewhere, javascript just considers it a string, so you won’t be able to access it directly. In addition, some older browsers do not have window.JSON, so you need to include json2.js in the library if you are worried about supporting older browsers.

0
source

Source: https://habr.com/ru/post/1484645/


All Articles