I have a json data coming from rest in following format:
{
"status_code": 200,
"data": {
"units": -1,
"unit_reference_ts": null,
"tz_offset": -4,
"unit": "day",
"countries": [{"country": "IN", "clicks": 12}]},
"status_txt": "OK"
}
I want to access the countries part and need to generate data in format like
{"IN":12, ......}
I dont know how to iterate through javascript, JSON array? Please help i am confused between methods which is the best & easiest that will work throughout the JSON?
I tried this:
$.each(response.countries, function(key, value) {
console.log(value.country + ": " + value.clicks);});
but it is showing me type error e is undefined...
Make sure you parse your JSON first (var data = JSON.parse(json)), then use a simple loop:
var obj = {};
for (var i = 0, l = data.data.countries.length; i < l; i++) {
var tmp = data.data.countries[i];
obj[tmp.country] = tmp.clicks
}
console.log(obj); // { IN: 12, UK: 123 }
DEMO
Since (from your edit) you're using jQuery, you'll probably need to do this (note that jQuery automatically parses JSON data if you retrieve it using one of its AJAX methods):
var obj = {};
$.each(response.data.countries, function(key, value) {
obj[value.country] = value.clicks;
});
If you want a string instead of an object, just JSON.stringify the obj:
var json = JSON.stringify(obj);
DEMO
Related
I have a below set of code to get the table data in an array and pass the same to servlet through ajax call. But i am getting null. Please someone help me on what my mistake / how to get the required data since i am new to this servlet and web app. So far i tried with some examples given in SO. but i am clueless to get my expected data.
var myTableArray = [];
$("table#itemtable tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
alert(myTableArray);
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data: {json:myTableArray},
success:function(data){
// codes....
},
});
Servlet code
String[] myJsonData = request.getParameterValues("json[]");
System.out.println("myJsonData.length"+myJsonData.length);
for (int i = 0; i < myJsonData.length; i++) {
String[] innerArray=myJsonData[i].split(",");
System.out.println(myJsonData[i]);
}
Send your Json data like this
$.ajax({
url:"insertmasteritem",
type:"POST",
dataType:'json',
data:myTableArray,
success:function(data){
// codes....
},
});
and In Servlet Class
JSONObject jsonObj= new JSONObject(request.getParameter("myTableArray"));
Iterator it = jsonObj.keys();
while(it.hasNext())
{
String jsonKey = (String)it.next();
String jsonValue = jsonObj.getString(jsonKey);
System.out.println(jsonKey + " --> " + jsonValue );
}
Well, you need to send a properly formatted JSON object (as a string) to the servlet. Possibly the easiest way to do this is to create some javascript objects and fill an array with these objects. The array data should then be
converted to a JSON string (using JSON.stringify). I'm going to hardcode object values (but you will get them from your table)
Javascript code
function generateJson(){
var myObjArr = [];
//you will typically have just one object (e.g. myObj, which you will fill in your ajax table loop
//myObj.v1 = v1_val;
//myObj.v2 = v2_val;
...
//myObjArr[i] = myObj; //
myObj1 = { "v1": "Orange", "v2": "ABC", "v3":10,"v4":"OK" };
myObj2 = { "v1": "Apple", "v2": "XYZ", "v3":25,"v4":"OK" };
myObjArr[0] = myObj1;
myObjArr[1] = myObj2;
var jsonObjStr = JSON.stringify(myObjArr);
//you can now use jsonObjStr to send your data to the servlet
// document.getElementById("json").innerHTML = jsonObjStr;//this is just added for testing purposes
}
The generated JSON
[{"v1":"Orange","v2":"ABC","v3":10,"v4":"OK"},{"v1":"Apple","v2":"XYZ","v3":25,"v4":"OK"}]
As you can see, the json string starts with a [ (which denotes an array). You may have to change this to start with a { (and with a } ) depending on how your JSON parser works ({} denote an object).
For the servlet part, it depends on the actual JSON parser you're using. Try to use some of the suggestions provided by others. I can provide some code using Jackson though, but you will have to add the Jackson library to your classpath.
why you are getting parameter value as JSON[]
String[] myJsonData = request.getParameterValues("json[]");
I have some JSON data being returned from an AJAX call. I then need to parse this data in javascript.
The data looks like so:
[
{
"id": "23",
"date_created": "2016-05-12 14:52:42"
},
{
"id": "25",
"date_created": "2016-05-12 14:52:42"
}
]
Why is it when i run this code on the data that i get multiple undefined's?
(var json being the variable holding my json data)
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.id);
}
However if i assign the json directly to the variable like so:
var json = [
{
"id": "23",
"date_created": "2016-05-12 14:52:42"
},
{
"id": "25",
"date_created": "2016-05-12 14:52:42"
}
];
Then it works fine!
Any ideas guys? Thanks
Make sure the JSON you're getting is not just stringified JSON. In that case do JSON.parse(json_string) and then loop and more processing.
Example:
var string_json = '[{"a":1},{"b":2}]'; // may be your API response is like this
var real_json = JSON.parse(string_json); // real_json contains actual objects
console.log(real_json[0].a, real_json[1].b); // logs 1 2
It is not a JSON that, you are using.
It's an object array.
When you get JSON, parse that JSON using method JSON.parse.
Assign this JSON to a variable and then use iteration over it...
Ex:
var json ='[{"id": "23","date_created": "2016-05-12 14:52:42"},{"id": "25","date_created": "2016-05-12 14:52:42"}]';
var parsedJson = JSON.parse(json);
for(var i = 0; i < parsedJson.length; i++) {
var obj = parsedJson[i];
console.log(obj.id);
}
Input of Json Object:
{"data":[
{"itemID":100,"Testcase1":"aaa","status":"Active"},
{"itemID":100,"Testcase1":"bbb","status":"No"},
{"itemID":100,"Testcase1":"ccc","status":"Active"},
{"itemID":101,"Testcase1":"zzz","status":"Active"}
]}
Expected Output of Json Object:
[{
"itemID":"100",
"Testcase1":"aaa",
"Testcase1":"bbb",
"Testcase1":"ccc",
"status":"Active",
"status":"No",
"status":"Active"
},
{
"itemID":"101",
"Testcase1":"zzz",
"status":"Active"
}]
anybody help me?
may be this helps you. This is not the correct way. Because duplicate key is not allowed in object. whatever as it your request. I have create a string of your required format.
please checkit FIDDLE
var dataVal={"data":[
{"itemID":100,"Testcase1":"aaa","status":"Active"},
{"itemID":100,"Testcase1":"bbb","status":"No"},
{"itemID":100,"Testcase1":"ccc","status":"Active"},
{"itemID":101,"Testcase1":"zzz","status":"Active"}
]};
var arrayVal = dataVal.data;
var DistinctID=[];
var resultStr="";
for (var elements in arrayVal){
if($.inArray(arrayVal[elements].itemID, DistinctID) == -1){
DistinctID.push(arrayVal[elements].itemID)
}
}
for (var items in DistinctID){
resultStr +='{"itemID":"'+DistinctID[items]+'",';
for (var elements in arrayVal){
if(arrayVal[elements].itemID==DistinctID[items]){
resultStr +='"Testcase1":"'+arrayVal[elements].Testcase1+'",';
resultStr +='"status":"'+arrayVal[elements].status+'",';
}
}
resultStr = resultStr.substring(0, resultStr.length - 1);
resultStr= resultStr+'},';
}
resultStr = resultStr.substring(0, resultStr.length - 1);
resultStr='['+resultStr+']';
alert((resultStr));
Assuming your "JSON Object" is a string, you can call JSON.parse() on it:
var data = '{"data":[{ ... }]}';
var parsed = JSON.parse(data);
This will give you data in the following structure:
Your expected output isn't a valid object. Object keys must be unique. An object cannot have three Testcase1 keys or three status keys.
You just have to extract objects from data object ?
Ok then, a pure JS solution :
var obj = {"data":[{"itemID":100,"Testcase1":"aaa","status":"Active"},
{"itemID":100,"Testcase1":"bbb","status":"No"},{"itemID":100,"Testcase1":"ccc","status":"Active"},
{"itemID":101,"Testcase1":"zzz","status":"Active"}]};
var newArray = [];
for( var i = 0; i < obj['data'].length; i++) {
newArray.push(obj['data'][i]);
}
And a live demo of that : http://jsfiddle.net/seLwmbyp/1/ (see the console for the result) > [Object, Object, Object, Object]
I am using Jquery Ui Autocomplete.
The problem I have is the data that is being returned from my api.
"{"d":{"results":[],"facets":{"facet_counts":{"Town":{"":0,"londonderry":136914,"london bridge":1,"london":8983316,"london colney":1}}},"__solr_time":3473457,"__ser_time":1564,"__t_time":1421,"__count":9120232,"__max_score":1.0}}"
I have run it through an online parser and it is valid, but I don't know how to access the list of towns with the corresponding number next to it.
Any help would be appreciated
I was able to access the Town "name" and number using:
var test = {
"d": {
"results": [],
"facets": {
"facet_counts": {
"Town": {
"": 0,
"londonderry": 136914,
"london bridge": 1,
"london": 8983316,
"london colney": 1
}
}
},
"__solr_time": 3473457,
"__ser_time": 1564,
"__t_time": 1421,
"__count": 9120232,
"__max_score": 1
}
}
for(var prop in test.d.facets.facet_counts.Town){
console.log(prop);
console.log(test.d.facets.facet_counts.Town[prop]);
}
Just run JSON.parse() on the string and then pull out the Town node.
var string; // the data string returned by API.
var dataObj = JSON.parse(string);
var Town = dataObj.d.facets.facet_counts.Town;
// access the properties as needed
var londonCount = Town.london;
var londonBridgeCount = Town['london bridge']; // need to use bracket notation to get this one
I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");